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);
    }
}

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

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

  • https://ma-study.blogspot.com/

  • I am very impressed with your writing Keonhacai I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!

  • I'm seriously impressed by this post. 🙌 Your writing style is not just engaging; it's downright addictive. Can't wait to see more post from you!

  • I've been searching for hours on this topic and finally found your post. <a href="https://google.sc/url?sa=t&url=https%3A%2F%2Fwww.mtclean.blog/">majorsite</a>, I have read your post and I am very impressed. We prefer your opinion and will visit this site frequently to refer to your opinion. When would you like to visit my site?

  • First of all, thank you for your post. <a href="https://google.rw/url?sa=t&url=https%3A%2F%2Fwww.mtclean.blog/">bitcoincasino</a> Your posts are neatly organized with the information I want, so there are plenty of resources to reference. I bookmark this site and will find your posts frequently in the future. Thanks again ^^

  • I'm writing on this topic these days, <a href="https://google.ru/url?sa=t&url=https%3A%2F%2Fwww.mtclean.blog/">safetoto</a>, but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts.

  • I've been looking for photos and articles on this topic over the past few days due to a school assignment, <a href="https://google.rs/url?sa=t&url=https%3A%2F%2Fwww.mtclean.blog/">casino online</a> and I'm really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks :D

  • I really enjoyed this article!

  • Your article has left a lasting impression on me, and I am grateful for the opportunity to learn from your work.

Add a Comment

As it will appear on the website

Not displayed

Your website