How to upload file to FTP server using C#

Posted by Anuraj on Tuesday, January 1, 2013 Reading time :1 minute

.Net .Net 3.0 / 3.5 .Net 4.0 Windows Forms

From .net framework 2.0 onwards .net supports FTP operations. Like HttpWebRequest and HttpWebResponse, for FTP operations, FtpWebRequest and FtpWebResponse classes are available, under System.Net namespace. Here is the code snippet, which will help you to upload a file to FTP server, using C#.

string url = "";
var ftpWebRequest = WebRequest.Create(url) as FtpWebRequest;
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpWebRequest.Credentials = 
    new NetworkCredential("username", "password");
byte[] fileData = GetFileData(@"C:\sample.txt");
using (var requestStream = ftpWebRequest.GetRequestStream())
    requestStream.Write(fileData, 0, fileData.Length);
var response = ftpWebRequest.GetResponse() as FtpWebResponse;


And here is the GetFileData function, which will return byte array from File.

using (var sr = new StreamReader(filename))
    return ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd());

From the response object, you can get the information about the status of the operation. You can either use StatusCode enum property or StatusDescription property. You can find more information about the status code enumeration on MSDN

Happy Coding :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon

BMC logoBuy me a coffee

Copyright © 2019 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub