Uploading a file via FTP in .net c#

uploadRemember when uploading a file via ftp was more a pain and took some third party components for stability? Now I have more trust in the .net method, below is a function I use for uploading a file:

You could call this function like:

ftpFile("current.jpg",@"C:\temp\some.jpg");

And the function:

private void ftpFile(string newFileName, string fileToUpload)
{
    string filename = fileToUpload;
    string ftpServerIP = "www.yourdomain.com/uploads";
    string ftpUserName = "yourftpuser";
    string ftpPassword = "yourftppass";

    FileInfo objFile = new FileInfo(filename);
    FtpWebRequest objFTPRequest;

    // Create a new FtpWebRequest object 
    objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + newFileName));

    // Set the ftp Credintials
    objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);

    // set keepalive to false
    objFTPRequest.KeepAlive = false;

    objFTPRequest.UseBinary = true;

    // Set content length
    objFTPRequest.ContentLength = objFile.Length;

    objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;

    // Set buffer size - below is about 16kb, you could increase...
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    // Opens a file to read (so you can write later)
    FileStream objFileStream = objFile.OpenRead();

    try
    {
        // Get file stream
        Stream objStream = objFTPRequest.GetRequestStream();

        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write binary file  
            objStream.Write(objBuffer, 0, len);

        }

        objStream.Close();
        objFileStream.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}

Hope someone enjoys!

As a side note, if you’re looking to do advanced ftp operations, checkout WinSCP. You might not be aware it handles SFTP, SSL, SSH and has great scripting functionality.

Uploading a file via FTP in .net c#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s