C# Code Snippet - Upload file to FTP Server

C# Code Snippet - Upload file to FTP Server

C# Code Snippet - Upload file to FTP Server

(C-Sharp) C# code snippet upload file to FTP Server. This method login to FTP server using username and password and upload the local file to given FTP location.

Bookmark:

C# Code Snippet - Upload file to FTP Server

This .Net C# code snippet upload file to FTP Server. To use this function simply provide the local file name to upload, upload path including host name, FTP username and FTP password. This function uses System.Net and System.IO namespaces to upload the file.

To upload file we create two streams, one for the FTP connection and another for the file we are reading from local disk to upload. These are the steps we take to upload a file: 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. This is the stream we will write to, open the file we are going to upload and get a stream to its data, read the file data from the input stream and write it into the request stream and close the uploaded file stream and the request stream.

/// <summary>
/// Methods to upload file to FTP Server
/// </summary>
/// <param name="_FileName">local source file name</param>
/// <param name="_UploadPath">Upload FTP path including Host name</param>
/// <param name="_FTPUser">FTP login username</param>
/// <param name="_FTPPass">FTP login password</param>
public void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass)
{
    System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName);

    // Create FtpWebRequest object from the Uri provided
    System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));

    // Provide the WebPermission Credintials
    _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);

    // By default KeepAlive is true, where the control connection is not closed
    // after a command is executed.
    _FtpWebRequest.KeepAlive = false;

    // set timeout for 20 seconds
    _FtpWebRequest.Timeout = 20000;

    // Specify the command to be executed.
    _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

    // Specify the data transfer type.
    _FtpWebRequest.UseBinary = true;

    // Notify the server about the size of the uploaded file
    _FtpWebRequest.ContentLength = _FileInfo.Length;

    // The buffer size is set to 2kb
    int buffLength = 2048;
    byte[] buff = new byte[buffLength];

    // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
    System.IO.FileStream _FileStream = _FileInfo.OpenRead();

    try
    {
        // Stream to which the file to be upload is written
        System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();

        // Read from the file stream 2kb at a time
        int contentLen = _FileStream.Read(buff, 0, buffLength);

        // Till Stream content ends
        while (contentLen != 0)
        {
            // Write Content from the file stream to the FTP Upload Stream
            _Stream.Write(buff, 0, contentLen);
            contentLen = _FileStream.Read(buff, 0, buffLength);
        }

        // Close the file stream and the Request Stream
        _Stream.Close();
        _Stream.Dispose();
        _FileStream.Close();
        _FileStream.Dispose();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}


Here is a simple example showing how to use above method (UploadFile) to upload file to FTP Server.

// Upload file using FTP
UploadFile("c:\\UploadFile.doc", "ftp://FTPHostName/UploadPath/UploadFile.doc", "UserName", "Password");


C# Keywords Used:

  • FileInfo
  • FtpWebRequest
  • Credentials
  • KeepAlive
  • Timeout
  • UploadFile
  • UseBinary
  • ContentLength
  • FileStream
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, Upload File, FTP Server, FTP Upload, FTP, FTP Web Request, File Stream
  • Programming Language : C# (C-Sharp)

External Resources:

Ngan :: January 21-2010 :: 08:31 AM

Thx for the snippet. Really helpful. It works.

Jonathan Reyes :: May 11-2010 :: 09:13 AM

Hi,

I tested this code in my project, It is works fine in the Local FTP server, but when I installed in Dev FTP server (Prod) the local source file it not reading it.

Please help me

Thanks in advance

Ross :: April 25-2011 :: 12:02 PM

Thanks alot, really appreciate this. Wicked website, i wish i has stumbled apon this sooner!

Moti :: February 15-2011 :: 11:58 AM

Very nice,works for me

Joseph :: June 30-2011 :: 02:14 PM

i am getting this error:

System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.IO.FileInfo..ctor(String fileName) at _Default.UploadFile(String _FileName, String _UploadPath, String _FTPUser, String _FTPPass) at _Default.Button1_Click(Object sender, EventArgs e) The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission The Zone of the assembly that failed was: MyComputer

Swamy :: October 11-2011 :: 06:59 PM

Do you have the same example which works for SFTP??? I tried using EnableSsl = True but didn't work, your help is appreciated

Leave a comment