Click here to Skip to main content
15,885,141 members
Articles / Programming Languages / C#
Article

FTP client library for C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (88 votes)
27 Mar 20031 min read 571K   14.5K   217   110
FTP client library for C#, including asynchronous operations.

Overview

Finding a fully working, lightweight FTP client, that had no GUI, was free, and came with source code, was difficult. This API is based on a work, Jaimon Mathew had done, and I have added some methods, cleaned up the code, debugged it and added some error handling, logging, debugging etc.

It is easy to use. Here is a code example:

C#
FtpClient ftp = new FtpClient(FtpServer,FtpUserName,FtpPassword);
ftp.Login();
ftp.Upload(@"C:\image.jpg");
ftp.Close();

Not so difficult now, is it? I am using it in my WebCamService list on this site, so if you want to see it in action, go here.

I started out wrapping fully the WinInet API, but it was such a labourous task that it made sense just to do the FTP. Since Microsoft has great support for HTTP, I could skip that, and later work on SMTP.

Features

  • Upload
  • Recursive upload
  • Download
  • Resume
  • Delete
  • Rename
  • Create directory
  • Asynchronous operation

Shortcomings

  • Not fully tested
  • No real error handling
  • No download recourse yet
  • Rename will overwrite, if the target already exists

Asynchronous operation

A little more advanced, the asynchronous operation is used when you need the job, to fork while your code continues over the method. All asynchronous methods start with Begin.

Using it is simple. You need a couple of things, an AsyncCallback object and a method which it handles.

C#
private FtpClient ftp = null;

private void UploadPicture(string imagePath)
{
    string FtpServer = ConfigurationSettings.AppSettings["FtpServer"];
    string FtpUserName = ConfigurationSettings.AppSettings["FtpUserName"];
    string FtpPassword = ConfigurationSettings.AppSettings["FtpPassword"];

    AsyncCallback callback = new AsyncCallback(CloseConnection);

    ftp = new FtpClient(FtpServer,FtpUserName,FtpPassword);
    ftp.Login();
    ftp.BeginUpload(imagePath, callback);
    ftp.Close();
}

private void CloseConnection(IAsyncResult result)
{
    Debug.WriteLine(result.IsCompleted.ToString());

    if ( ftp != null ) ftp.Close();
        ftp = null;
} 

When the upload finishes or throws an exception, the CloseConnection method will be called.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect support.com
Australia Australia

Comments and Discussions

 
GeneralDon't loose your time... Pin
tiusho30-Nov-05 22:27
tiusho30-Nov-05 22:27 
GeneralRe: Don't loose your time... Pin
Jeff Firestone2-Dec-05 7:18
Jeff Firestone2-Dec-05 7:18 
GeneralRe: Don't loose your time... Pin
thirteenthmonth4-Jan-07 17:26
thirteenthmonth4-Jan-07 17:26 
GeneralRe: Don't loose your time... Pin
User 2575527-May-09 0:24
User 2575527-May-09 0:24 
GeneralRe: Don't loose your time... Pin
nietzsche4413-Sep-07 22:19
nietzsche4413-Sep-07 22:19 
GeneralRe: Don't loose your time... Pin
Baeltazor16-Jan-10 19:43
Baeltazor16-Jan-10 19:43 
Generalerror,while ftp.GetFileList(); Pin
lovemory23-Aug-05 17:50
lovemory23-Aug-05 17:50 
AnswerRe: error,while ftp.GetFileList(); Pin
Sprotty11-Oct-05 0:13
Sprotty11-Oct-05 0:13 
There does appear to be a problem here.

The NLST request is made, and the response comes back on the response connection, however its only read until 'some' data is receved. It should continue reading until the response code comes back on the main connection.

This seems to fix it, but Im not entirely happy using the sleep....But time was short, and I didn't have the time to do any better!

Regards Simon Sprott

		public string[] GetFileList(string mask)<br />
		{<br />
			if ( !this.loggedin ) this.Login();<br />
<br />
			Socket cSocket = createDataSocket();<br />
<br />
			this.sendCommand("NLST " + mask);<br />
<br />
			if(!(this.resultCode == 150 || this.resultCode == 125)) throw new FtpException(this.result.Substring(4));<br />
<br />
			this.message = "";<br />
<br />
			DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);<br />
<br />
			int respCode = 0;<br />
			while( timeout > DateTime.Now && this.PeekResponse(ref respCode))<br />
			{<br />
				int bytes = cSocket.Receive(buffer, buffer.Length, 0);<br />
				if (bytes == 0)<br />
					System.Threading.Thread.Sleep(10); <br />
				this.message += ASCII.GetString(buffer, 0, bytes);<br />
			}<br />
			string[] msg = this.message.Replace("\r","").Split('\n');<br />
<br />
			cSocket.Close();<br />
<br />
			if ( this.message.IndexOf( "No such file or directory" ) != -1 )<br />
				msg = new string[]{};<br />
<br />
			this.readResponse();<br />
<br />
			if ( this.resultCode != 226 )<br />
				msg = new string[]{};<br />
			//	throw new FtpException(result.Substring(4));<br />
<br />
			return msg;<br />
		}<br />
<br />
		private bool PeekResponse(ref int respCode)<br />
		{<br />
			byte[] respBuffer = new byte[3];<br />
<br />
			int bytesRead = clientSocket.Receive(respBuffer, 0, 3, SocketFlags.Peek);<br />
			if (bytesRead != 3)<br />
				return false;<br />
<br />
			string strResp = ASCII.GetString(respBuffer, 0, 3);<br />
<br />
			respCode = int.Parse( strResp );<br />
			return true;<br />
		}<br />
<br />


-- modified at 6:14 Tuesday 11th October, 2005
GeneralRe: error,while ftp.GetFileList(); Pin
Patrice Dargenton27-Jun-06 0:40
Patrice Dargenton27-Jun-06 0:40 
GeneralRe: error,while ftp.GetFileList(); Pin
tmck7-Mar-07 5:25
tmck7-Mar-07 5:25 
GeneralRe: error,while ftp.GetFileList(); Pin
ti_hugo31-May-07 1:31
ti_hugo31-May-07 1:31 
GeneralRe: error,while ftp.GetFileList(); Pin
Patrick Mortara20-Nov-07 6:25
Patrick Mortara20-Nov-07 6:25 
GeneralProxy Support for FTP client Pin
drkalucard3-May-05 23:40
drkalucard3-May-05 23:40 
GeneralAnother free, open-source .NET FTP component Pin
h_c_a_andersen11-Nov-04 11:45
h_c_a_andersen11-Nov-04 11:45 
QuestionHave any body here actualy looked at the code? Pin
Arnt1-Nov-04 12:31
Arnt1-Nov-04 12:31 
GeneralNot working Pin
agolovan29-Sep-04 14:50
agolovan29-Sep-04 14:50 
GeneralRe: Not working Pin
mohit bhat18-Nov-04 3:22
mohit bhat18-Nov-04 3:22 
GeneralRe: Not working Pin
Anonymous24-Jan-05 19:06
Anonymous24-Jan-05 19:06 
GeneralIt doesn't work with the IIS FTP server if a welcome message is set Pin
Justin Couto9-Jun-04 6:15
Justin Couto9-Jun-04 6:15 
GeneralRe: It doesn't work with the IIS FTP server if a welcome message is set Pin
Jose Lopes da Cruz25-Aug-04 5:34
Jose Lopes da Cruz25-Aug-04 5:34 
GeneralRe: It doesn't work with the IIS FTP server if a welcome message is set Pin
GoToSleep22-Sep-05 5:41
GoToSleep22-Sep-05 5:41 
QuestionNo File Uploading??? Pin
_stormbringer_20-May-04 10:15
_stormbringer_20-May-04 10:15 
Generalasync Pin
toni113-May-04 4:13
toni113-May-04 4:13 
GeneralBetter version. Pin
Dan Glass10-May-04 11:55
Dan Glass10-May-04 11:55 
GeneralRe: Better version. Pin
Anonymous11-May-04 5:32
Anonymous11-May-04 5:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.