Vous êtes sur la page 1sur 8

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

A Rahim Khans Blog

Sharing Database Driven Software Development Experiences and Views

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


About I f you have thesediculties ads 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/" 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;

1 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

File Upload to FTP:

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

FtpWebRequest requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/Destinatio 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/" + 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();

2 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

} 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 2010 09/03 CATEGORY C# TAGS File list FTP Directory File List Local Directory FTP C# FTP Delete FTP Download FTP upload Write comment Write comment Comments RSS Trackback ( 2 ) Comments ( 29 ) 1. Ian September 13th, 2010 REPLY QUOTE 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 le, and my requirement is for uploading multiple les. So my requirement is like this: 1. have a C# FTP program that can run una ended from a task scheduler to upload all les in a

3 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

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 a empts, connection and session logs to specied email address. 4. If possible -Username and password should not be hard coded in program, or contained in plain text conguration le. 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 2. A Rahim Khan September 14th, 2010 REPLY QUOTE hi lan following code snippet will list le names from a local folder. ********************** string localPath = @G:\FTPTrialLocalPath\; string[] les = Directory.GetFiles(localPath); foreach (string lepath in les) { string leName = Path.GetFileName(lepath); Console.WriteLine(leName); // Here you can use le upload code for each lename } *********************** hope this will help you. Thanks 3. ma hew December 20th, 2010 REPLY QUOTE i tried using the code posted below to delete a le from my web space, but i am ge ing this error: The remote server returned an error: (550) File unavailable (e.g., le not found, no access). here is the code, do you know what may be going on? private void DeleteFile() { string leName = test.txt; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp://ftp.ma hew-swanson.com /storage/ + leName); request.Method = WebRequestMethods.Ftp.DeleteFile; request.Credentials = new NetworkCredential(FTPusername, FTPpassword);

4 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } 4. A Rahim Khan December 21st, 2010 REPLY QUOTE ma hew most probably, request cant locate the le. The code snippet is ok and should work. you need to conrm that the le is in ftp location. Ma hew December 21st, 2010 REPLY QUOTE Yeah I gured 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 le I want, but I cannot gure out how to display the directory you are currently viewing when you retrieve a le list. Ma hew December 21st, 2010 REPLY QUOTE Never mind, I have gured 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 5. ishita September 1st, 2011 REPLY QUOTE Is there any direct way to upload a whole folder to ftp using c#???? A Rahim Khan September 2nd, 2011 REPLY QUOTE I have not get anything like that. 6. hoanglamdz September 14th, 2011 REPLY QUOTE your share helpful for me,thank a lot,im 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 A Rahim Khan September 14th, 2011 REPLY QUOTE any time, khan.rahim@gmail.com is my email address. send me your queries, i will try to gure out if i can. thanks 7. Abdul wadood September 20th, 2011 REPLY QUOTE

5 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

Hi Raheem! I want to upload le on multiple ftps on one click, i dont know how to do? Please share with me your ides, i am waiting for your response. 8. Marlon Peterson Silva September 28th, 2011 REPLY QUOTE Thank you veeery much. savp October 19th, 2011 REPLY QUOTE how can i download remote folders and subfolders, les within it using ftp . c# onlinecashproject October 20th, 2011 REPLY QUOTE Thanks a lot for the code ;-) noushad November 8th, 2011 REPLY QUOTE good example Imran Bashir November 25th, 2011 REPLY QUOTE It was very helpful code thanks a lot Rahim Keith Miller January 24th, 2012 REPLY QUOTE 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 les (no wonder). I have adapted this code into my own library and added test cases that test folder creation, le upload and le delete. I still need to gure 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. Id like to oer anyone who reads this thread/post a free copy of WinReminders (just e-mail us; sales or support at WinReminders dot com) and well be happy to oblige. This is in recognition of this useful sample post by Rahim. 14. marshal February 10th, 2012 REPLY QUOTE bhaia, how to upload le 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 eld

9.

10.

11.

12.

13.

6 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

A Rahim Khan February 10th, 2012 REPLY QUOTE the path you mentioned is not a ftp path. just move the le as if you move the le in a directory in same computer. google for C# code to move a le and use it with shared directory. moreover u will required write permission to copy les in that directory. hope now you can solve your problem. 15. Ethan February 14th, 2012 REPLY QUOTE Hey , this article was a great help. Ive learned lots! Thanks!!! madhu February 28th, 2012 REPLY QUOTE I found Something simple, here is detailed Explanation h p://path4tech.blogspot.in/2012/02/upload-le-to-ftp-server-by-using.html Teri April 24th, 2012 REPLY QUOTE Thank you so much for this very simple explanation. I used the upload method and the rst time it worked perfect! sophorn June 19th, 2012 REPLY QUOTE Hi, rst at all thanks for your useful code. One question is: How can i enable percentage during Download/Upload le with FtpWebRequest object? Nixa Testa July 10th, 2012 REPLY QUOTE Thank You, Rahim. I rst used the example code from the MSDN library and was about to freak out because the les where always corrupted after up- or download. Following Your samples everything works well from the rst time. It is incredible how the lousy lamers at Microsoft are not even able to provide a working sample for their own components. 20. Raja August 2nd, 2012 REPLY QUOTE I would like to know how to prompt open/save dialog while downloading a word le from server via ftp. Raja August 2nd, 2012 REPLY QUOTE if i hard code the server path with le name means the les are downloading, if i pass the le name

16.

17.

18.

19.

21.

7 of 8

11-Nov-12 3:02 PM

File Download, Upload, Delete in FTP Location using C# A Rahim ...

http://khanrahim.wordpress.com/2010/09/03/file-download-upload-del...

dynamically means im ge ing an error [The remote server returned an error: (550) File unavailable (e.g., le not found, no access)]. How to resolve it? Thanks in advance 22. Shaunie Evans October 2nd, 2012 REPLY QUOTE Thanks!! the downloader was just what I needed :) anitha October 16th, 2012 REPLY QUOTE Very helpful good job. thanks November 2nd, 2012 REPLY QUOTE thanks!!!

23.

24.

TrackBack URL 1. September 3rd, 2010 Trackback from : File Download, Upload, Delete in FTP Location using C# A Rahim | ftp 2. January 3rd, 2011 Trackback from : 2010 in review A Rahim Khans Blog

Blog at WordPress.com. | Theme: monochrome by mono-lab.

8 of 8

11-Nov-12 3:02 PM

Vous aimerez peut-être aussi