FtpWebRequest Class
Implements a File Transfer Protocol (FTP) client.
Assembly: System (in System.dll)
The FtpWebRequest type exposes the following members.
| Name | Description | |
|---|---|---|
|
AuthenticationLevel | Gets or sets values indicating the level of authentication and impersonation used for this request. (Inherited from WebRequest.) |
|
CachePolicy | Gets or sets the cache policy for this request. (Inherited from WebRequest.) |
|
ClientCertificates | Gets or sets the certificates used for establishing an encrypted connection to the FTP server. |
|
ConnectionGroupName | Gets or sets the name of the connection group that contains the service point used to send the current request. (Overrides WebRequest.ConnectionGroupName.) |
|
ContentLength | Infrastructure. Gets or sets a value that is ignored by the FtpWebRequest class. (Overrides WebRequest.ContentLength.) |
|
ContentOffset | Gets or sets a byte offset into the file being downloaded by this request. |
|
ContentType | Infrastructure. Always throws a NotSupportedException. (Overrides WebRequest.ContentType.) |
|
Credentials | Gets or sets the credentials used to communicate with the FTP server. (Overrides WebRequest.Credentials.) |
|
DefaultCachePolicy | Defines the default cache policy for all FTP requests. |
|
EnableSsl | Gets or sets a Boolean that specifies that an SSL connection should be used. |
|
Headers | Infrastructure. Gets an empty WebHeaderCollection object. (Overrides WebRequest.Headers.) |
|
ImpersonationLevel | Gets or sets the impersonation level for the current request. (Inherited from WebRequest.) |
|
KeepAlive | Gets or sets a Boolean value that specifies whether the control connection to the FTP server is closed after the request completes. |
|
Method | Gets or sets the command to send to the FTP server. (Overrides WebRequest.Method.) |
|
PreAuthenticate | Infrastructure. Always throws a NotSupportedException. (Overrides WebRequest.PreAuthenticate.) |
|
Proxy | Gets or sets the proxy used to communicate with the FTP server. (Overrides WebRequest.Proxy.) |
|
ReadWriteTimeout | Gets or sets a time-out when reading from or writing to a stream. |
|
RenameTo | Gets or sets the new name of a file being renamed. |
|
RequestUri | Gets the URI requested by this instance. (Overrides WebRequest.RequestUri.) |
|
ServicePoint | Gets the ServicePoint object used to connect to the FTP server. |
|
Timeout | Gets or sets the number of milliseconds to wait for a request. (Overrides WebRequest.Timeout.) |
|
UseBinary | Gets or sets a Boolean value that specifies the data type for file transfers. |
|
UseDefaultCredentials | Infrastructure. Always throws a NotSupportedException. (Overrides WebRequest.UseDefaultCredentials.) |
|
UsePassive | Gets or sets the behavior of a client application's data transfer process. |
| Name | Description | |
|---|---|---|
|
Abort | Terminates an asynchronous FTP operation. (Overrides WebRequest.Abort().) |
|
BeginGetRequestStream | Begins asynchronously opening a request's content stream for writing. (Overrides WebRequest.BeginGetRequestStream(AsyncCallback, Object).) |
|
BeginGetResponse | Begins sending a request and receiving a response from an FTP server asynchronously. (Overrides WebRequest.BeginGetResponse(AsyncCallback, Object).) |
|
CreateObjRef | Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) |
|
EndGetRequestStream | Ends a pending asynchronous operation started with BeginGetRequestStream. (Overrides WebRequest.EndGetRequestStream(IAsyncResult).) |
|
EndGetResponse | Ends a pending asynchronous operation started with BeginGetResponse. (Overrides WebRequest.EndGetResponse(IAsyncResult).) |
|
Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) |
|
Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) |
|
GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) |
|
GetLifetimeService | Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
|
GetObjectData | Infrastructure. Populates a SerializationInfo with the data needed to serialize the target object. (Inherited from WebRequest.) |
|
GetRequestStream | Retrieves the stream used to upload data to an FTP server. (Overrides WebRequest.GetRequestStream().) |
|
GetResponse | Returns the FTP server response. (Overrides WebRequest.GetResponse().) |
|
GetType | Gets the Type of the current instance. (Inherited from Object.) |
|
InitializeLifetimeService | Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) |
|
MemberwiseClone() | Creates a shallow copy of the current Object. (Inherited from Object.) |
|
MemberwiseClone(Boolean) | Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) |
|
ToString | Returns a string that represents the current object. (Inherited from Object.) |
| Name | Description | |
|---|---|---|
|
ISerializable.GetObjectData | Infrastructure. When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest. (Inherited from WebRequest.) |
To obtain an instance of FtpWebRequest, use the Create method. You can also use the WebClient class to upload and download information from an FTP server. Using either of these approaches, when you specify a network resource that uses the FTP scheme (for example, "ftp://contoso.com") the FtpWebRequest class provides the ability to programmatically interact with FTP servers.
The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to <UserLoginDirectory>/path.
You must have a valid user name and password for the server or the server must allow anonymous logon. You can specify the credentials used to connect to the server by setting the Credentials property or you can include them in the UserInfo portion of the URI passed to the Create method. If you include UserInfo information in the URI, the Credentials property is set to a new network credential with the specified user name and password information.
Caution
|
|---|
|
Unless the EnableSsl property is true, all data and commands, including your user name and password information, are sent to the server in clear text. Anyone monitoring network traffic can view your credentials and use them to connect to the server. If you are connecting to an FTP server that requires credentials and supports Secure Sockets Layer (SSL), you should set EnableSsl to true. |
You must have WebPermission to access the FTP resource; otherwise, a SecurityException exception is thrown.
Specify the FTP command to send to the server by setting the Method property to a value defined in the WebRequestMethods.Ftp structure. To transmit text data, change the UseBinary property from its default value (true) to false. For details and restrictions, see Method.
When using an FtpWebRequest object to upload a file to a server, you must write the file content to the request stream obtained by calling the GetRequestStream method or its asynchronous counterparts, the BeginGetRequestStream and EndGetRequestStream methods. You must write to the stream and close the stream before sending the request.
Requests are sent to the server by calling the GetResponse method or its asynchronous counterparts, the BeginGetResponse and EndGetResponse methods. When the requested operation completes, an FtpWebResponse object is returned. The FtpWebResponse object provides the status of the operation and any data downloaded from the server.
You can set a time-out value for reading or writing to the server by using the ReadWriteTimeout property. If the time-out period is exceeded, the calling method throws a WebException with WebExceptionStatus set to Timeout.
When downloading a file from an FTP server, if the command was successful, the contents of the requested file are available in the response object's stream. You can access this stream by calling the GetResponseStream method. For more information, see FtpWebResponse.
If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made through the specified proxy. If the specified proxy is an HTTP proxy, only the DownloadFile, ListDirectory, and ListDirectoryDetails commands are supported.
Only downloaded binary content is cached; that is, content received using the DownloadFile command with the UseBinary property set to true.
Multiple FtpWebRequests reuse existing connections, if possible.
For more information about the FTP protocol, see RFC 959, "File Transfer Protocol," available at http://www.rfc-editor.org/.
The following code example demonstrates deleting a file from an FTP server.
public static bool DeleteFileOnServer(Uri serverUri) { // The serverUri parameter should use the ftp:// scheme. // It contains the name of the server file that is to be deleted. // Example: ftp://contoso.com/someFile.txt. // if (serverUri.Scheme != Uri.UriSchemeFtp) { return false; } // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri); request.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse) request.GetResponse(); Console.WriteLine("Delete status: {0}",response.StatusDescription); response.Close(); return true; }
The following code example demonstrates downloading a file from an FTP server by using the WebClient class.
public static bool DisplayFileFromServer(Uri serverUri) { // The serverUri parameter should start with the ftp:// scheme. if (serverUri.Scheme != Uri.UriSchemeFtp) { return false; } // Get the object used to communicate with the server. WebClient request = new WebClient(); // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com"); try { byte [] newFileData = request.DownloadData (serverUri.ToString()); string fileString = System.Text.Encoding.UTF8.GetString(newFileData); Console.WriteLine(fileString); } catch (WebException e) { Console.WriteLine(e.ToString()); } return true; }
The following code example demonstrates using asynchronous operations to upload a file to an FTP server.
using System; using System.Net; using System.Threading; using System.IO; namespace Examples.System.Net { public class FtpState { private ManualResetEvent wait; private FtpWebRequest request; private string fileName; private Exception operationException = null; string status; public FtpState() { wait = new ManualResetEvent(false); } public ManualResetEvent OperationComplete { get {return wait;} } public FtpWebRequest Request { get {return request;} set {request = value;} } public string FileName { get {return fileName;} set {fileName = value;} } public Exception OperationException { get {return operationException;} set {operationException = value;} } public string StatusDescription { get {return status;} set {status = value;} } } public class AsynchronousFtpUpLoader { // Command line arguments are two strings: // 1. The url that is the name of the file being uploaded to the server. // 2. The name of the file on the local machine. // public static void Main(string[] args) { // Create a Uri instance with the specified URI string. // If the URI is not correctly formed, the Uri constructor // will throw an exception. ManualResetEvent waitObject; Uri target = new Uri (args[0]); string fileName = args[1]; FtpState state = new FtpState(); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); request.Method = WebRequestMethods.Ftp.UploadFile; // This example uses anonymous logon. // The request is anonymous by default; the credential does not have to be specified. // The example specifies the credential only to // control how actions are logged on the server. request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com"); // Store the request in the object that we pass into the // asynchronous operations. state.Request = request; state.FileName = fileName; // Get the event to wait on. waitObject = state.OperationComplete; // Asynchronously get the stream for the file contents. request.BeginGetRequestStream( new AsyncCallback (EndGetStreamCallback), state ); // Block the current thread until all operations are complete. waitObject.WaitOne(); // The operations either completed or threw an exception. if (state.OperationException != null) { throw state.OperationException; } else { Console.WriteLine("The operation completed - {0}", state.StatusDescription); } } private static void EndGetStreamCallback(IAsyncResult ar) { FtpState state = (FtpState) ar.AsyncState; Stream requestStream = null; // End the asynchronous call to get the request stream. try { requestStream = state.Request.EndGetRequestStream(ar); // Copy the file contents to the request stream. const int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; int count = 0; int readBytes = 0; FileStream stream = File.OpenRead(state.FileName); do { readBytes = stream.Read(buffer, 0, bufferLength); requestStream.Write(buffer, 0, readBytes); count += readBytes; } while (readBytes != 0); Console.WriteLine ("Writing {0} bytes to the stream.", count); // IMPORTANT: Close the request stream before sending the request. requestStream.Close(); // Asynchronously get the response to the upload request. state.Request.BeginGetResponse( new AsyncCallback (EndGetResponseCallback), state ); } // Return exceptions to the main application thread. catch (Exception e) { Console.WriteLine("Could not get the request stream."); state.OperationException = e; state.OperationComplete.Set(); return; } } // The EndGetResponseCallback method // completes a call to BeginGetResponse. private static void EndGetResponseCallback(IAsyncResult ar) { FtpState state = (FtpState) ar.AsyncState; FtpWebResponse response = null; try { response = (FtpWebResponse) state.Request.EndGetResponse(ar); response.Close(); state.StatusDescription = response.StatusDescription; // Signal the main application thread that // the operation is complete. state.OperationComplete.Set(); } // Return exceptions to the main application thread. catch (Exception e) { Console.WriteLine ("Error getting response."); state.OperationException = e; state.OperationComplete.Set(); } } } }
-
WebPermission
for accessing the resource referenced by this request. Associated enumeration: Connect.
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
- 4/2/2012
- Shekhar R. Gurav
*or* you can enumerate them in the .def file (or mix and match).
Note that just creating a .def file in your project with a matching name to your dll's name is *not* enough. You must also specify it as the "Module Definition File" to the Linker. See http://betterlogic.com/roger/?p=3112
- 8/2/2010
- rogerdpack2
- 7/7/2011
- Thomas Lee
Imports System
Imports System.Collections.Generic
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.Net.Security
Public Class FTP
Public UserName As String = String.Empty
Public Password As String = String.Empty
Public KeepAlive As Boolean = False
Public UseSSL As Boolean = True
Public m_FTPSite As String = String.Empty
Public Property FTPSite As String
Get
Return m_FTPSite
End Get
Set(ByVal value As String)
m_FTPSite = value
If Not m_FTPSite.EndsWith("/") Then m_FTPSite += "/"
End Set
End Property
Private m_CurDir As String = String.Empty
Public Property CurrentDirectory As String
Get
Return m_CurDir
End Get
Set(ByVal value As String)
m_CurDir = value
If Not m_CurDir.EndsWith("/") And m_CurDir <> "" Then
m_CurDir += "/"
m_CurDir = m_CurDir.TrimStart("/".ToCharArray())
End If
End Set
End Property
Public Sub New()
End Sub
Public Sub New(ByVal sFTPSite As String, ByVal sUserName As String, ByVal sPassword As String)
UserName = sUserName
Password = sPassword
FTPSite = sFTPSite
End Sub
Public Function ValidateServerCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
If sslPolicyErrors = sslPolicyErrors.RemoteCertificateChainErrors Then
Return False
ElseIf sslPolicyErrors = sslPolicyErrors.RemoteCertificateNameMismatch Then
Dim z As System.Security.Policy.Zone = System.Security.Policy.Zone.CreateFromUrl(CType(sender, HttpWebRequest).RequestUri.ToString)
If z.SecurityZone = System.Security.SecurityZone.Intranet Or z.SecurityZone = System.Security.SecurityZone.MyComputer Then
Return True
End If
Return False
End If
Return True
End Function
Public Function GetFileList(ByVal CurDirectory As String, ByVal StartsWith As String, ByVal EndsWith As String) As List(Of String)
CurrentDirectory = CurDirectory
Return GetFileList(StartsWith, EndsWith)
End Function
Public Function GetFileList(ByVal StartsWith As String, ByVal EndsWith As String) As List(Of String)
Dim oFTP As FtpWebRequest = CType(FtpWebRequest.Create(FTPSite & CurrentDirectory), FtpWebRequest)
oFTP.Credentials = New NetworkCredential(UserName, Password)
oFTP.KeepAlive = KeepAlive
oFTP.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
oFTP.Method = WebRequestMethods.Ftp.ListDirectory
Dim response As FtpWebResponse = CType(oFTP.GetResponse, FtpWebResponse)
Dim sr As StreamReader = New StreamReader(response.GetResponseStream)
Dim str As String = sr.ReadLine
Dim oList As New List(Of String)
While str IsNot Nothing
If str.StartsWith(StartsWith) And str.EndsWith(EndsWith) Then
oList.Add(str)
End If
str = sr.ReadLine
End While
sr.Close()
response.Close()
oFTP = Nothing
Return oList
End Function
Public Function GetFile(ByVal Name As String, ByVal DestFile As String) As Boolean
Dim oFTP As FtpWebRequest = CType(FtpWebRequest.Create(FTPSite & CurrentDirectory & Name), FtpWebRequest)
oFTP.Credentials = New NetworkCredential(UserName, Password)
oFTP.Method = WebRequestMethods.Ftp.DownloadFile
oFTP.KeepAlive = KeepAlive
oFTP.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
oFTP.UseBinary = True
Dim response As FtpWebResponse = CType(oFTP.GetResponse, FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim fs As New FileStream(DestFile, FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 1
While read <> 0
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
End While
responseStream.Close()
fs.Flush()
fs.Close()
responseStream.Close()
response.Close()
oFTP = Nothing
Return True
End Function
Public Function UploadFile(ByVal oFile As FileInfo) As Boolean
Dim ftpRequest As FtpWebRequest
Dim ftpResponse As FtpWebResponse
Try
ftpRequest = CType(FtpWebRequest.Create(FTPSite + CurrentDirectory + oFile.Name), FtpWebRequest)
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.Proxy = Nothing
ftpRequest.UseBinary = True
ftpRequest.Credentials = New NetworkCredential(UserName, Password)
ftpRequest.KeepAlive = KeepAlive
ftpRequest.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Dim fileContents(oFile.Length) As Byte
Using fr As FileStream = oFile.OpenRead
fr.Read(fileContents, 0, Convert.ToInt32(oFile.Length))
End Using
Using writer As Stream = ftpRequest.GetRequestStream
writer.Write(fileContents, 0, fileContents.Length)
End Using
ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
ftpResponse.Close()
ftpRequest = Nothing
Return True
Catch ex As WebException
Return False
End Try
End Function
Public Function DeleteFile(ByVal Name As String) As Boolean
Dim oFTP As FtpWebRequest
oFTP = CType(FtpWebRequest.Create(FTPSite + CurrentDirectory + Name), FtpWebRequest)
oFTP.Credentials = New NetworkCredential(UserName, Password)
oFTP.Method = WebRequestMethods.Ftp.DeleteFile
oFTP.KeepAlive = KeepAlive
oFTP.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
oFTP.UseBinary = True
Dim response As FtpWebResponse = CType(oFTP.GetResponse, FtpWebResponse)
Dim oStat As FtpStatusCode = response.StatusCode
response.Close()
oFTP = Nothing
Return True
End Function
End Class
- 5/20/2010
- beauXjames
- 7/7/2011
- Thomas Lee
- 4/19/2011
- Janga
<#
.SYNOPSIS
This script deletes a file from an FTP Server
.DESCRIPTION
This script is a rewrite of an MSDN Sample
.NOTES
File Name : Remove-FtpFile.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 2.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
MSDN sample posted tot:
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
.EXAMPLE
PSH [C:\foo]: .\Remove-FtpFile.ps1
Delete status: 250 DELE command successful.
#>
$ServerUri = New-Object System.Uri "ftp://www.reskit.net/powershell/foo.txt"
# The serverUri parameter should use the ftp:// scheme.
# It contains the name of the server file that is to be deleted.
# Example: ftp://contoso.com/someFile.txt.
if ($ServerUri.Scheme -ne [system.Uri]::UriSchemeFtp) {
" Bad URI"; return
}
# Get the object used to communicate with the server.
$request = [system.Net.FtpWebRequest]::Create($serverUri)
$request.Method = [System.Net.WebRequestMethods+ftp]::Deletefile
$Request.Credentials = New-Object System.Net.NetworkCredential "anonymous","tfl@psp.co.uk"
$response = $request.GetResponse()
"Delete status: {0}" -f $response.StatusDescription
$response.Close();
- 10/4/2010
- Thomas Lee
I installed the latest broadcom drivers, but the devicemgr shows two devices with driverproblems. The devices are BTHENUM\{84a1e9b8-12ba-4a9c-8ab0-a43784e0d149}
and BTHENUM\{24df01a9-3e4f-4c9f-9f66-5aa8ab14f8f4}_LOCALMFG&0000.
Please help, kind regards.
[tfl - 02 08 10] Hi - and thanks for your post.You should post questions like this to the Technet Forums at http://forums.microsoft.com/technet or the MS Newsgroups at http://www.microsoft.com/communities/newsgroups/en-us/. You are much more likely get a quick response using the forums than through the Community Content. For specific help about:
Exchange : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.exchange%2C&
SQL Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.sqlserver%2C&
Windows : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.windows%2C&
Windows Server : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public.windows.server%2C&
Virtual Server : http://groups.google.com/group/microsoft.public.virtualserver/topics?lnk
Full Public : http://groups.google.com/groups/dir?sel=usenet%3Dmicrosoft.public%2C&
- 8/2/2010
- Thomas Lee
Caution