This documentation is archived and is not being maintained.

FtpWebRequest Class

Implements a File Transfer Protocol (FTP) client.

Namespace:  System.Net
Assembly:  System (in System.dll)

'Declaration
Public NotInheritable Class FtpWebRequest _
	Inherits WebRequest

The FtpWebRequest type exposes the following members.

  NameDescription
Public propertyAuthenticationLevelGets or sets values indicating the level of authentication and impersonation used for this request. (Inherited from WebRequest.)
Public propertyCachePolicyGets or sets the cache policy for this request. (Inherited from WebRequest.)
Public propertyClientCertificatesGets or sets the certificates used for establishing an encrypted connection to the FTP server.
Public propertyConnectionGroupNameGets or sets the name of the connection group that contains the service point used to send the current request. (Overrides WebRequest.ConnectionGroupName.)
Public propertyContentLengthInfrastructure. Gets or sets a value that is ignored by the FtpWebRequest class. (Overrides WebRequest.ContentLength.)
Public propertyContentOffsetGets or sets a byte offset into the file being downloaded by this request.
Public propertyContentTypeInfrastructure. Always throws a NotSupportedException. (Overrides WebRequest.ContentType.)
Public propertyCredentialsGets or sets the credentials used to communicate with the FTP server. (Overrides WebRequest.Credentials.)
Public propertyStatic memberDefaultCachePolicyDefines the default cache policy for all FTP requests.
Public propertyEnableSslGets or sets a Boolean that specifies that an SSL connection should be used.
Public propertyHeadersInfrastructure. Gets an empty WebHeaderCollection object. (Overrides WebRequest.Headers.)
Public propertyImpersonationLevelGets or sets the impersonation level for the current request. (Inherited from WebRequest.)
Public propertyKeepAliveGets or sets a Boolean value that specifies whether the control connection to the FTP server is closed after the request completes.
Public propertyMethodGets or sets the command to send to the FTP server. (Overrides WebRequest.Method.)
Public propertyPreAuthenticateInfrastructure. Always throws a NotSupportedException. (Overrides WebRequest.PreAuthenticate.)
Public propertyProxyGets or sets the proxy used to communicate with the FTP server. (Overrides WebRequest.Proxy.)
Public propertyReadWriteTimeoutGets or sets a time-out when reading from or writing to a stream.
Public propertyRenameToGets or sets the new name of a file being renamed.
Public propertyRequestUriGets the URI requested by this instance. (Overrides WebRequest.RequestUri.)
Public propertyServicePointGets the ServicePoint object used to connect to the FTP server.
Public propertyTimeoutGets or sets the number of milliseconds to wait for a request. (Overrides WebRequest.Timeout.)
Public propertyUseBinaryGets or sets a Boolean value that specifies the data type for file transfers.
Public propertyUseDefaultCredentialsInfrastructure. Always throws a NotSupportedException. (Overrides WebRequest.UseDefaultCredentials.)
Public propertyUsePassiveGets or sets the behavior of a client application's data transfer process.
Top

  NameDescription
Public methodAbortTerminates an asynchronous FTP operation. (Overrides WebRequest.Abort.)
Public methodBeginGetRequestStreamBegins asynchronously opening a request's content stream for writing. (Overrides WebRequest.BeginGetRequestStream(AsyncCallback, Object).)
Public methodBeginGetResponseBegins sending a request and receiving a response from an FTP server asynchronously. (Overrides WebRequest.BeginGetResponse(AsyncCallback, Object).)
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodEndGetRequestStreamEnds a pending asynchronous operation started with BeginGetRequestStream. (Overrides WebRequest.EndGetRequestStream(IAsyncResult).)
Public methodEndGetResponseEnds a pending asynchronous operation started with BeginGetResponse. (Overrides WebRequest.EndGetResponse(IAsyncResult).)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetObjectDataInfrastructure. Populates a SerializationInfo with the data needed to serialize the target object. (Inherited from WebRequest.)
Public methodGetRequestStreamRetrieves the stream used to upload data to an FTP server. (Overrides WebRequest.GetRequestStream.)
Public methodGetResponseReturns the FTP server response. (Overrides WebRequest.GetResponse.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate methodISerializable.GetObjectDataInfrastructure. When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the WebRequest. (Inherited from WebRequest.)
Top

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 noteCaution

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 Shared Function DeleteFileOnServer(ByVal serverUri As Uri) As Boolean
    ' 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 Then
        Return False
    End If
    ' Get the object used to communicate with the server.
    Dim request As FtpWebRequest = CType(WebRequest.Create(serverUri), FtpWebRequest)
    request.Method = WebRequestMethods.Ftp.DeleteFile

    Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
    Console.WriteLine("Delete status: {0}", response.StatusDescription)
    response.Close()
    Return True
End Function


The following code example demonstrates downloading a file from an FTP server by using the WebClient class.


Public Shared Function DisplayFileFromServer(ByVal serverUri As Uri) As Boolean
    ' The serverUri parameter should start with the ftp:// scheme.
    If serverUri.Scheme <> Uri.UriSchemeFtp Then
        Return False
    End If
    ' Get the object used to communicate with the server.
    Dim request As New WebClient()

    ' This example assumes the FTP site uses anonymous logon.
    request.Credentials = New NetworkCredential("anonymous", "janeDoe@contoso.com")
    Try
        Dim newFileData() As Byte = request.DownloadData(serverUri.ToString())
        Dim fileString As String = Encoding.UTF8.GetString(newFileData)
        Console.WriteLine(fileString)
    Catch e As WebException
        Console.WriteLine(e.ToString())
    End Try
    Return True
End Function


The following code example demonstrates using asynchronous operations to upload a file to an FTP server.


Imports System
Imports System.Net
Imports System.Threading

Imports System.IO
Namespace Examples.System.Net
    Public Class FtpState
        Private wait As ManualResetEvent
        Private _request As FtpWebRequest
        Private _fileName As String
        Private _operationException As Exception = Nothing
        Private status As String

        Public Sub New()
            wait = New ManualResetEvent(False)
        End Sub

        Public ReadOnly Property OperationComplete() As ManualResetEvent
            Get
                Return wait
            End Get
        End Property

        Public Property Request() As FtpWebRequest
            Get
                Return _request
            End Get
            Set(ByVal value As FtpWebRequest)
                _request = value
            End Set
        End Property

        Public Property FileName() As String
            Get
                Return _fileName
            End Get
            Set(ByVal value As String)
                _fileName = value
            End Set
        End Property
        Public Property OperationException() As Exception
            Get
                Return _operationException
            End Get
            Set(ByVal value As Exception)
                _operationException = value
            End Set
        End Property
        Public Property StatusDescription() As String
            Get
                Return status
            End Get
            Set(ByVal value As String)
                status = value
            End Set
        End Property
    End Class
    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 Shared Sub Main(ByVal args() As String)
            ' Create a Uri instance with the specified URI string.
            ' If the URI is not correctly formed, the Uri constructor
            ' will throw an exception.
            Dim waitObject As ManualResetEvent

            Dim target As New Uri(args(0))
            Dim fileName As String = args(1)
            Dim state As New FtpState()
            Dim request As FtpWebRequest = CType(WebRequest.Create(target), FtpWebRequest)
            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(AddressOf EndGetStreamCallback), state)

            ' Block the current thread until all operations are complete.
            waitObject.WaitOne()

            ' The operations either completed or threw an exception.
            If state.OperationException IsNot Nothing Then
                Throw state.OperationException
            Else
                Console.WriteLine("The operation completed - {0}", state.StatusDescription)
            End If
        End Sub
        Private Shared Sub EndGetStreamCallback(ByVal ar As IAsyncResult)
            Dim state As FtpState = CType(ar.AsyncState, FtpState)

            Dim requestStream As Stream = Nothing
            ' End the asynchronous call to get the request stream.
            Try
                requestStream = state.Request.EndGetRequestStream(ar)
                ' Copy the file contents to the request stream.
                Const bufferLength As Integer = 2048
                Dim buffer(bufferLength - 1) As Byte
                Dim count As Integer = 0
                Dim readBytes As Integer = 0
                Dim stream As FileStream = File.OpenRead(state.FileName)
                Do
                    readBytes = stream.Read(buffer, 0, bufferLength)
                    requestStream.Write(buffer, 0, readBytes)
                    count += readBytes
                Loop 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(AddressOf EndGetResponseCallback), state)
                ' Return exceptions to the main application thread.
            Catch e As Exception
                Console.WriteLine("Could not get the request stream.")
                state.OperationException = e
                state.OperationComplete.Set()
                Return
            End Try

        End Sub

        ' The EndGetResponseCallback method  
        ' completes a call to BeginGetResponse.
        Private Shared Sub EndGetResponseCallback(ByVal ar As IAsyncResult)
            Dim state As FtpState = CType(ar.AsyncState, FtpState)
            Dim response As FtpWebResponse = Nothing
            Try
                response = CType(state.Request.EndGetResponse(ar), FtpWebResponse)
                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 e As Exception
                Console.WriteLine("Error getting response.")
                state.OperationException = e
                state.OperationComplete.Set()
            End Try
        End Sub
    End Class
End Namespace


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

  • 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.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: