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
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
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
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();
}
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.
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.
ı have same problem, could you pls write how to solve problem?
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
Is there any direct way to upload a whole folder to ftp using c#????
I have not get anything like that.
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
any time, khan.rahim@gmail.com is my email address. send me your queries, i will try to figure out if i can.
thanks
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.
Thank you veeery much.
how can i download remote folders and subfolders, files within it using ftp . c#
Thank´s a lot for the code ;-)
good example
It was very helpful code thanks a lot Rahim
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.
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.
Hey , this article was a great help. I’ve learned lots! Thanks!!!
I found Something simple,
here is detailed Explanation
http://path4tech.blogspot.in/2012/02/upload-file-to-ftp-server-by-using.html
Thank you so much for this very simple explanation. I used the upload method and the first time it worked perfect!
Hi, first at all thanks for your useful code.
One question is: How can i enable percentage during Download/Upload file with FtpWebRequest object?
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.
I would like to know how to prompt open/save dialog while downloading a word file from server via ftp.
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…
Thanks!! the downloader was just what I needed :)
Very helpful good job.
thanks!!!
what is the difference among fileinfo, filestream and stream reader classes?
code snippets were really help ul
thanx
good working
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.
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.
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.
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??
very good post really helpfull
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..
how to upload file on ftp server
hi , I need to get list of files from FTP server, based on search string provided.
haiii i want know how to move one ftp file to another ftp file directory
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
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)
Thanks a alot for this simple and concret code.