FtpWebRequest Class

System.Net Namespace

Note: The WebRequest and WebResponse classes, and the associated ProtocolViolationException, WebClient, CredentialCache, HttpRequestException, and HttpResponseException classes are deprecated. For new development, use the HttpClient class.

Provides an application programming interface (API) to programmatically communicate with servers that use the File Transfer Protocol (FTP).

Syntax

public class FtpWebRequest : System.Net.WebRequest

Inheritance Hierarchy

System.Object
System.MarshalByRefObject
System.Net.WebRequest
System.Net.FtpWebRequest

Remarks

The FtpWebRequest class allows you to send requests to FTP servers. It supports standard FTP operations such as uploading, downloading, listing directories, and creating directories. You typically create an instance of FtpWebRequest by calling the static method WebRequest.Create(string requestUri) with an FTP URI (e.g., "ftp://ftp.example.com/file.txt").

You can specify FTP commands to be sent to the server using the Method property. For example, setting Method to "STOR" prepares the request to upload a file, and "RETR" prepares to download a file.

Authentication can be handled by setting the Credentials property.

Constructors

The FtpWebRequest class has no public constructors. You must create instances using WebRequest.Create.

Properties

Name Description
EnableSsl Gets or sets a value indicating whether to use SSL for the FTP connection. true to use SSL; otherwise, false.
Credentials Gets or sets the NetworkCredential used to authenticate the request to the server.
Method Gets or sets the FTP command to be sent to the server (e.g., "STOR", "RETR", "DELE", "NLST").
RequestUri Gets the Uri of the resource that is requested. (Inherited from WebRequest)
UseBinary Gets or sets a value indicating whether to use binary mode for transfers. true for binary mode; false for ASCII mode. Defaults to true.
ContentLength Gets or sets the length of the content sent in the body of the request. (Inherited from WebRequest)
ContentType Gets or sets the type of content in the request body. (Inherited from WebRequest)

Methods

BeginGetRequestStream

Begins an asynchronous request to write to a file on the FTP server.

public virtual System.IAsyncResult BeginGetRequestStream(System.AsyncCallback callback, object state)
EndGetRequestStream

Ends an asynchronous request to write to a file on the FTP server.

public virtual System.IO.Stream EndGetRequestStream(System.IAsyncResult asyncResult)
BeginGetResponse

Begins an asynchronous request to return a FtpWebResponse object.

public virtual System.IAsyncResult BeginGetResponse(System.AsyncCallback callback, object state)
EndGetResponse

Ends an asynchronous request to return a FtpWebResponse object.

public virtual System.Net.WebResponse EndGetResponse(System.IAsyncResult asyncResult)
GetRequestStream

Gets an outgoing stream to write data to the FTP server.

public override System.IO.Stream GetRequestStream()
GetResponse

Gets an incoming response from the FTP server.

public override System.Net.WebResponse GetResponse()

Example Usage

The following example demonstrates how to upload a file to an FTP server using FtpWebRequest.

using System;
using System.IO;
using System.Net;

public class FtpUploadExample
{
    public static void UploadFile(string ftpUri, string username, string password, string localFilePath, string remoteFileName)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri + "/" + remoteFileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(username, password);
        request.UseBinary = true;
        request.ContentLength = new FileInfo(localFilePath).Length;

        using (FileStream fileStream = File.OpenRead(localFilePath))
        {
            using (Stream requestStream = request.GetRequestStream())
            {
                fileStream.CopyTo(requestStream);
            }
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload complete, status: {response.StatusDescription}");
        }
    }

    public static void Main(string[] args)
    {
        string ftpUrl = "ftp://your_ftp_server.com";
        string ftpUser = "your_username";
        string ftpPass = "your_password";
        string localFile = @"C:\path\to\your\local\file.txt";
        string remoteFile = "uploaded_file.txt";

        try
        {
            UploadFile(ftpUrl, ftpUser, ftpPass, localFile, remoteFile);
            Console.WriteLine("File uploaded successfully.");
        }
        catch (WebException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
            if (ex.Response != null)
            {
                Console.WriteLine($"Status Code: {((FtpWebResponse)ex.Response).StatusCode}");
                Console.WriteLine($"Status Description: {((FtpWebResponse)ex.Response).StatusDescription}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}

See Also