File Download, Upload, Delete in FTP Location using C#

If you have difficulties with FTP File operations, you are at the right place. I am going to present some self explanatory code snippets in C# to accomplish FTP FILE operations like downloading, uploading and deleting.


using System.Net;


First of all, this directive is mandatory for FTP Operations.

File Download From FTP:


string localPath = @"G:\FTPTrialLocalPath\";
string fileName = "arahimkhan.txt";

FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://localhost/Source/" + fileName);
requestFileDownload.Credentials = new NetworkCredential("khanrahim", "arkhan22");
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create);  

int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);               

while (bytesRead > 0)
{
  writeStream.Write(buffer, 0, bytesRead);
  bytesRead = responseStream.Read(buffer, 0, Length);
}   

responseStream.Close();             
writeStream.Close();

requestFileDownload = null;
responseFileDownload = null;


File Upload to FTP:


string localPath = @"G:\FTPTrialLocalPath\";
string fileName = "arahimkhan.txt";

FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/Destination/" + fileName);
requestFTPUploader.Credentials = new NetworkCredential("khanrahim", "arkhan22");
requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile;

FileInfo fileInfo = new FileInfo(localPath + fileName);
FileStream fileStream = fileInfo.OpenRead();

int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];

Stream uploadStream = requestFTPUploader.GetRequestStream();
int contentLength = fileStream.Read(buffer, 0, bufferLength);

while (contentLength != 0)
{
 uploadStream.Write(buffer, 0, contentLength);
 contentLength = fileStream.Read(buffer, 0, bufferLength);
}
                    
uploadStream.Close();
fileStream.Close();

requestFTPUploader = null;


File Delete From FTP:


string fileName = "arahimkhan.txt";

FtpWebRequest requestFileDelete = (FtpWebRequest)WebRequest.Create("ftp://localhost/Source/" + fileName);
requestFileDelete.Credentials = new NetworkCredential("khanrahim", "arkhan22");
requestFileDelete.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse responseFileDelete = (FtpWebResponse)requestFileDelete.GetResponse();


Retrieve File List from FTP Directory:


FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost/Source");
request.Credentials = new NetworkCredential("khanrahim", "arkhan22");
request.Method = WebRequestMethods.Ftp.ListDirectory;

StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());

string fileName = streamReader.ReadLine();

while (fileName != null)
{
 Console.Writeline(fileName );
 fileName = streamReader.ReadLine();
}

request = null;
streamReader = null;


using System.IO;


You have to use this directive for Local File Operation.

Retrieve File List from Local Directory:


string localPath = @"G:\FTPTrialLocalPath\";

string[] files = Directory.GetFiles(localPath);

foreach (string filepath in files)
{
  string fileName = Path.GetFileName(filepath);
  Console.WriteLine(fileName);
}

You can download source code.

Thanks
A Rahim Khan

    • Ian
    • September 13th, 2010

    Rahim -I mostly need to use your upload code snippet however I am not clear for my requirement how to put pieces together. Your upload example shows uploading a single file, and my requirement is for uploading multiple files.

    So my requirement is like this:

    1. have a C# FTP program that can run unattended from a task scheduler to upload all files in a directory/sub directories on my local machine to a remote ftp server in a secure datacenter. The data center uses SSL (VeriSign).

    2. Provide connection and session logging capability for troubleshooting problems.

    3. Email via SMTP after uploads are completed/or failed after 3 attempts, connection and session logs to specified email address.

    4. If possible -Username and password should not be hard coded in program, or contained in plain text configuration file. Note: we have MS: Windows 2003 Server, Active Directory, IIS, and SQL Server available in our environment, and use SSL from VeriSign . Can this be accomplished?
    Or is the only way to do this, is to hard code username and password in program and specify “EnableSsl to true”

    Can you please help. I am new to C#.

    Thanks kindly -Ian

  1. hi lan

    following code snippet will list file names from a local folder.

    **********************
    string localPath = @”G:\FTPTrialLocalPath\”;

    string[] files = Directory.GetFiles(localPath);

    foreach (string filepath in files)
    {
    string fileName = Path.GetFileName(filepath);
    Console.WriteLine(fileName);

    // Here you can use file upload code for each filename
    }
    ***********************

    hope this will help you.

    Thanks

    • matthew
    • December 20th, 2010

    i tried using the code posted below to delete a file from my web space, but i am getting this error: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

    here is the code, do you know what may be going on?

    private void DeleteFile() {
    string fileName = “test.txt”;

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(“ftp://ftp.matthew-swanson.com/storage/” + fileName);
    request.Method = WebRequestMethods.Ftp.DeleteFile;
    request.Credentials = new NetworkCredential(FTPusername, FTPpassword);

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    }

  2. matthew

    most probably, request can’t locate the file. The code snippet is ok and should work. you need to confirm that the file is in ftp location.

      • Matthew
      • December 21st, 2010

      Yeah I figured it out, i set the default location for the FTP account to the wrong directory. I almost have a working FTP client now, I can upload, download, delete any file I want, but I cannot figure out how to display the directory you are currently viewing when you retrieve a file list.

        • tomas
        • November 17th, 2013

        ı have same problem, could you pls write how to solve problem?

      • Matthew
      • December 21st, 2010

      Never mind, I have figured out a workaround, thank you for your help, I am not much of a programmer, but thanks to you I have my own FTP program

    • ishita
    • September 1st, 2011

    Is there any direct way to upload a whole folder to ftp using c#????

    • hoanglamdz
    • September 14th, 2011

    your share helpful for me,thank a lot,i’m a beginner in C# .Net,can you give me your contact,i want to make friend with you :),Hope you reply early.This is my email kerenxki@gmail.com

    • Abdul wadood
    • September 20th, 2011

    Hi Raheem!
    I want to upload file on multiple ftps on one click, i don’t know how to do? Please share with me your ides, i am waiting for your response.

    • Marlon Peterson Silva
    • September 28th, 2011

    Thank you veeery much.

    • savp
    • October 19th, 2011

    how can i download remote folders and subfolders, files within it using ftp . c#

  3. Thank´s a lot for the code ;-)

    • noushad
    • November 8th, 2011

    good example

  4. It was very helpful code thanks a lot Rahim

  5. Some good general sample code. I like the fact the upload code breaks the upload into 2KB chunks, which some other sample code on the web fails to consider, and corresponding user comments say that the other code fails for larger files (no wonder).

    I have adapted this code into my own library and added test cases that test folder creation, file upload and file delete. I still need to figure out folder delete, but that is the last piece of the puzzle for me. Thanks to this post it has been a very short exercise for me to implement my own version.

    I’d like to offer anyone who reads this thread/post a free copy of WinReminders (just e-mail us; sales or support at WinReminders dot com) and we’ll be happy to oblige. This is in recognition of this useful sample post by Rahim.

  6. bhaia,

    how to upload file using C# into lan directory such (\\192.168.10.22 ? any idea, I am looking for this code for last few days but no luck.

    Please assist me as I am a novice coder in this field

    • the path you mentioned is not a ftp path. just move the file as if you move the file in a directory in same computer. google for C# code to move a file and use it with shared directory. moreover u will required write permission to copy files in that directory. hope now you can solve your problem.

  7. Hey , this article was a great help. I’ve learned lots! Thanks!!!

    • madhu
    • February 28th, 2012

    I found Something simple,
    here is detailed Explanation
    http://path4tech.blogspot.in/2012/02/upload-file-to-ftp-server-by-using.html

    • Teri
    • April 24th, 2012

    Thank you so much for this very simple explanation. I used the upload method and the first time it worked perfect!

    • sophorn
    • June 19th, 2012

    Hi, first at all thanks for your useful code.
    One question is: How can i enable percentage during Download/Upload file with FtpWebRequest object?

  8. Thank You, Rahim.
    I first used the example code from the MSDN library and was about to freak out because the files where always corrupted after up- or download.
    Following Your samples everything works well from the first time.

    It is incredible how the lousy lamers at Microsoft are not even able to provide a working sample for their own components.

    • Raja
    • August 2nd, 2012

    I would like to know how to prompt open/save dialog while downloading a word file from server via ftp.

    • Raja
    • August 2nd, 2012

    if i hard code the server path with file name means the files are downloading, if i pass the file name dynamically means i’m getting an error [The remote server returned an error: (550) File unavailable (e.g., file not found, no access)]. How to resolve it? Thanks in advance…

  9. Thanks!! the downloader was just what I needed :)

    • anitha
    • October 16th, 2012

    Very helpful good job.

    • thanks
    • November 2nd, 2012

    thanks!!!

    • zofi
    • November 27th, 2012

    what is the difference among fileinfo, filestream and stream reader classes?

    • Sidra
    • November 30th, 2012

    code snippets were really help ul
    thanx

    • Hans Bettmacher
    • March 17th, 2013

    good working

  10. An impressive share! I have just forwarded this onto a co-worker who had been doing
    a little research on this. And he in fact bought
    me breakfast because I found it for him… lol. So
    allow me to reword this…. Thank YOU for the meal!
    ! But yeah, thanx for spending the time to talk about
    this matter here on your web site.

  11. Hey! Someone in my Facebook group shared this website with us
    so I came to check it out. I’m definitely loving the information. I’m
    bookmarking and will be tweeting this to my followers! Exceptional blog and fantastic style and design.

    • Dheeraj Sawlani
    • August 23rd, 2013

    I want to delete a folder at ftp, not a single file, the folder can contain multiple number of files, how to do that.. i tried with RemoveDirectory Method , its not working..giving error.
    Any help is appreciated.

    • Nk
    • December 13th, 2013

    FTP is best and easy way to file transfer… And any way if your port is open then hackers search your FTP port (like 80 bydefault) and hack your important data.

    Other hand, If you change the FTP port sequentially hack ‘ll be difficult but not impossible.

    can i upload file using HTTPS tunnel??

  12. very good post really helpfull

    • lakshmi
    • April 27th, 2015

    Hi ,

    how do we implement resume upload functionality using fileupload control without using any third party controls? i have used code to upload file in chunks of byte. but when i removed network connection in between of upload process, target file with size whatever uploaded till that time was not there..is writestream did not save the file untill it writes whole file ? please help me..

    • prachi
    • July 17th, 2015

    how to upload file on ftp server

    • kamlesh
    • September 28th, 2015

    hi , I need to get list of files from FTP server, based on search string provided.

  13. haiii i want know how to move one ftp file to another ftp file directory

    • Sangamesh
    • April 7th, 2016

    Hi, Rahim
    i am trying to upload file from local folder to remote computer of same network, i am executing your code but it is giving error in this line as Stream uploadStream = requestFTPUploader.GetRequestStream(); as “Unable to connect to the remote server”
    pls help me to overcome this error

    • Gowtham
    • August 12th, 2016

    Hi,
    I am able to read FTP Files successfully however if the file has spaces in file name I am unable to get the response stream , instead, I am getting the file not found exception.
    Ex: ” EEPAY 181.CSV” (Notice the space b/w EEPAY and 181)

    • msbisht
    • June 15th, 2017

    Thanks a alot for this simple and concret code.

  1. September 3rd, 2010
  2. January 3rd, 2011
  3. December 9th, 2013

Leave a reply to Hans Bettmacher Cancel reply