FTP File transfer using C#

In this article, learn how to perform FTP file transfer using C#.


FTP File transfer using C#

To transfer files using FTP in C#, you can use the FtpWebRequest and FtpWebResponse classes that are included in the System.Net namespace. Here is an example of how to upload a file to an FTP server:

Example 1:

using System;

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

namespace FtpExample {
    class Program {
        static void Main(string[] args) {
            string ftpUrl = "ftp://example.com/upload/file.txt";
            string userName = "ftp_user";
            string password = "ftp_password";

            string localFilePath = "C:\\Users\\UserName\\Desktop\\file.txt";

            // Create a FTP request object
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Set FTP credentials
            request.Credentials = new NetworkCredential(userName, password);

            // Read the file contents into a byte array
            byte[] fileContents;
            using (StreamReader reader = new StreamReader(localFilePath)) {
                fileContents = Encoding.UTF8.GetBytes(reader.ReadToEnd());
            }

            // Write the file to the FTP server
            using (Stream writer = request.GetRequestStream()) {
                writer.Write(fileContents, 0, fileContents.Length);
            }

            // Get the FTP server response
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("File upload status: {0}", response.StatusDescription);
            response.Close();
        }
    }
}

In this example, the FtpWebRequest object is used to upload a file to the FTP server at the specified URL. The Method property is set to WebRequestMethods.Ftp.UploadFile to indicate that a file should be uploaded. The FTP credentials are set using the Credentials property of the FtpWebRequest object.

The contents of the file are read into a byte array using a StreamReader object, which is then written to the FTP server using a Stream object obtained from the GetRequestStream method of the FtpWebRequest object.

Finally, the GetResponse method is called to retrieve the FTP server’s response, and the response is displayed in the console.

Note that you may also need to handle errors and exceptions that can occur during the file transfer process, such as network errors or incorrect FTP credentials.

Example 2

using System;

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

namespace FtpExample {
    class Program {
        static void Main(string[] args) {
            string ftpServerUrl = "ftp://example.com";
            string ftpUsername = "username";
            string ftpPassword = "password";

            string localFilePath = "C:\\example.txt";
            string remoteFilePath = "/example.txt";

            // Create FtpWebRequest object
            FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(ftpServerUrl + remoteFilePath);
            ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
            ftpWebRequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

            // Copy the contents of the file to the request stream
            using (FileStream localFileStream = new FileStream(localFilePath, FileMode.Open))
            using (Stream requestStream = ftpWebRequest.GetRequestStream())
            {
                localFileStream.CopyTo(requestStream);
            }

           // Get the FTP server's response
           FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
           Console.WriteLine("Upload File Complete, status {0}", ftpWebResponse.StatusDescription);
           ftpWebResponse.Close();

        }
    }
}

Example 3 (only function):

using System;

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

public static void UploadFile(string ftpServer, string filePath, string userName, string password)
{
    // Create a new FTP request object.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + Path.GetFileName(filePath));

    // Set the request's credentials and other properties.
    request.Credentials = new NetworkCredential(userName, password);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = true;
    request.KeepAlive = false;

    // Read the file to be uploaded into a byte array.
    byte[] fileContents = File.ReadAllBytes(filePath);

    // Write the file contents to the FTP server.
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContents, 0, fileContents.Length);
    }

    // Get the response from the FTP server.
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    // Display the status code returned by the server.
    Console.WriteLine("Upload status: {0}", response.StatusDescription);

    // Clean up the response object.
    response.Close();
}


Example 4:

using System;

string ftpServer = "ftp://ftp.example.com/";
string ftpUsername = "username";
string ftpPassword = "password";
string filePath = @"C:\path\to\file.txt";
string remoteFilename = "file.txt";

// Create a WebRequest object to connect to the FTP server
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + remoteFilename);

// Set the method to UploadFile and specify the FTP credentials
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

// Read the file data into a byte array
byte[] fileData = File.ReadAllBytes(filePath);

// Set the content length of the file data
request.ContentLength = fileData.Length;

// Get a reference to the request stream and write the file data to it
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileData, 0, fileData.Length);
}

// Get a reference to the response object and print the status code
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload status: {0}", response.StatusDescription);
response.Close();




– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Share this:
We will be happy to hear your thoughts

      Leave a reply

      www.troubleshootyourself.com
      Logo