Upload any file to FTP server via C#

Microsoft has a C# example of uploading file to FTP server in MSDN https://msdn.microsoft.com/en-us/library/ms229715(v=vs.100).aspx and Microsoft docs https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp:

// Copy the contents of the file to the request stream.  
StreamReader sourceStream = new StreamReader("testfile.txt");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

It uses StreamReader to read a string from a text file, then encode the string to bytes and upload.

This document’s title has a general title “Upload Files with FTP". However, this approach with StreamReader only works with text file. If the above code is used to upload a binary file, like a picture, the uploaded file on FTP server becomes corrupted. The general options are:

1. Call File.ReadAllBytes to read the bytes, and write to request stream:

byte[] fileContents = File.ReadAllBytes(filePath);
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
}

2. Use FileStream to read the file, and copy the file stream to request stream:

public static async Task<FtpStatusCode> FtpUploadAsync(string uri, string userName, string password, string filePath)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(userName, password);
    // request.UsePassive is true by default.

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    using (Stream requestStream = request.GetRequestStream())
    {
        await fileStream.CopyToAsync(requestStream);
    }

    using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
    {
        return response.StatusCode;
    }
}

3. Use WebClient, which wraps all the above work flow:

public static async Task FtpUploadAsync(string uri, string userName, string password, string filePath)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.Credentials = new NetworkCredential(userName, password);
        await webClient.UploadFileTaskAsync(uri, WebRequestMethods.Ftp.UploadFile, filePath);
    }
}

6 Comments

  • Hi,

    Great stuff !. It was nicely explained and very useful. Thanks a lot. :)

    Seb.

  • Uploading a file to an FTP server fails.

    I have a small C# winform in which I generate some text files and then move them to an ftp server. When I try to move them to the production server it fails under

    The remote server returned an error: (530) Not logged in.

    If I log in to the ftp via cmd/ftp with the same ftp address, username and password, everything is ok. I also installed a local ftp server on my machine and tested it to see if perhaps my code is generating the error, but locally it works like a charm, I have the problem only with the production ftp server. Below is my code to connect and upload the files to the ftp server:

    string[] FileName = Directory.GetFiles(outputpath);

    foreach (string txtFile in FileName)
    {
    FileInfo toUpload = new FileInfo(txtFile);

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + tbFTPAddress.Text + @"//" + toUpload.Name);

    request.Credentials = new NetworkCredential(tbFTPUserName.Text.Trim(), tbFTPPassword.Text.Trim());

    request.Method = WebRequestMethods.Ftp.UploadFile;

    Stream ftpStream = request.GetRequestStream();
    FileStream file = File.OpenRead(txtFile);

    int length = 1024;
    byte[] buffer = new byte[length];
    int bytesRead = 0;

    try
    {
    do
    {
    bytesRead = file.Read(buffer, 0, length);
    ftpStream.Write(buffer, 0, bytesRead);
    }
    while (bytesRead != 0);

    file.Close();
    ftpStream.Close();
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message, "Error encountered!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
    if (file != null) file.Close();
    if (ftpStream != null) ftpStream.Close();
    }
    }
    The error comes at: Stream ftpStream = request.GetRequestStream();

    Any ideas?

    Thanks!


  • hello. im working in winform.
    i have a problem in the same line but th exception is: System.Net.WebException: 'No se puede resolver el nombre remoto: 'pruebaftp.pagexyz.com'' i´ve try all ways the uri and its ok.. what could hapen?


  • The FTP Request
    To connect to the FTP server we can use the FtpWebRequest C# object under the System.Net namespace. The object is created with the FtpWebRequest.Create() function. Note that the function will ask for a URL to connect to, the format to write the URL: [FTP Address] + "/" + [Filename of file to upload].

  • Create a FtpWebRequest object.
    Set the FtpWebRequest.Method property to UploadFile.
    Set the FtpWebRequest.Credentials property to our login information.
    Get the request stream of the FtpWebRequest object. ...
    Open the file we're going to upload and get a stream to its data.

  • Microsoft has a C# example of uploading file to FTP server in MSDN https://msdn.microsoft.com/en-us/library/ms229715(v=vs.100).aspx and Microsoft docs https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp: // Copy the contents of the file to the request stream.

Add a Comment

As it will appear on the website

Not displayed

Your website