Click here to Skip to main content
Licence Public Domain
First Posted 11 Jul 2005
Views 626,559
Bookmarked 227 times

C# FTP Client Library

By | 5 May 2006 | Article
Easy to use FTP client library with features in mind.

Introduction

This code is for implementing FTP client capabilities in applications without needing to know the underlying protocol. The general idea is 'easy to use' while giving you access to (mainly) information you would also want to know about the upload/download process. One of the things that pushed me towards writing it was a lack of pre-existing code that lets you have progress information. The DoDownload() and DoUpload() functions return the bytes received, and the total bytes and file size info are available as well for any further calculations you might want to do.

There is no screenshot of the demo application because the purpose of this code is not to provide you with a functioning application. There is a demo application though, just to demonstrate how I intended the code to be used. It's a small command line FTP client with very basic functionality that is meant to provide a good reference on how to use the features the ftplib code provides.

Using the code

See the sample application for the best example of using it. I've made notes in the comments about how to use it, and there is info in the comments of ftplib.cs about adding on to it, functions you should call to keep from re-inventing the wheel, and how to deal with critical and non-critical errors.

Opening a Connection and Changing to a Directory

Opening a connection is pretty straightforward as you see below:

// create an instance of the ftp library
FTP ftplib = new FTP();

try 
{
    // there are server, user and password properties
    // that can be set within the ftplib object as well
    // those properties are actually set when
    // you call the Connect(server, user, pass) function
    ftplib.Connect("ftp.microsoft.com", 
                   "anonymous", 
                   "anonymous@noplace.net");
    ftplib.ChangeDir("directory_foo/");
}
catch(Exception ex)
{    
    Console.WriteLine(ex.Message);
}

Downloading a File

Downloading and uploading are pretty much the exact same process. The only real difference is using the upload methods in place of the download methods.

try
{ 
    int perc =  0;
    
    // open the file with resume support if it already exists, the last 
    // peram should be false for no resume
    ftplib.OpenDownload("somefile_on_the_server.txt", true);
    while(ftplib.DoDownload() > 0) 
    { 
        perc = (int)((ftplib.BytesTotal * 100)  / ftplib.FileSize); 
        Console.Write("\rDownloading: {0}/{1} {2}%", 
          ftplib.BytesTotal, ftplib.FileSize, perc);
        Console.Out.Flush();
    }
    Console.WriteLine("");
}
catch(Exception ex) 
{ 
    Console.WriteLine("");
    Console.WriteLine(ex.Message);
}

Listing Files

Listing files is a very simple process as well. Not all servers are guaranteed to return a file listing in the same format either. An example is, MS IIS can be configured to return a long UNIX like directory listing or another one with some tags like <DIR> in them. Be prepared to handle either one when processing the list returned.

try
{
    foreach(string f in ftplib.List())
        Console.WriteLine(f);
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

Points of Interest

The DoUpload() and DoDownload() functions have had significant changes made. They no longer return the percentage complete in a transfer. The former approach was OK when I had originally started this code for a specific task, but to make it more compatible with various FTP server implementations, it had to be changed. The problem that existed with this approach is that file sizes are not always available, which makes progress monitoring not possible in all cases. To avoid potential problems, I have changed the code to return the bytes sent/received in a transfer. Provided the file sizes are available, all the information needed to calculate the progress is available within the class. Any code based on the old methods has to be changed to cope with the new process of a file transfer. See the example code in this article or in the FTP client included with the source, for more information on how to implement a file transfer.

History

I wrote this code with FTPFactory.cs as a reference. You can find FTPFactory.cs on this site. I've listed the authors of FTPFactory.cs in the ftplib.cs source as well as their email addresses. Any and all bugs with this code should not be emailed to them.

Updates

  • 7/28/2005

    I've updated the code a bit for speed improvements. Those of you who may be using the older code will notice a significant increase in speed for file listings, file transfers, or anything else that requires a data channel. See the ChangeLog.txt file in the project for more information on what has been changed.

  • 08/23/2005

    There is a new developer! Filipe Madureira has submitted quite a few bug fixes that resolve issues mainly with the MS IIS FTP service, but it also corrects one issue that existed with all FTP services. Thanks for the help on improving the code Filipe! See the ChangeLog.txt for detailed information on what has been changed. You will also notice that all of the source includes the BSD license with the advertising clause omitted. We were approached about licensing so I had to do something. I think the BSD license is the right choice to make everyone happy. The intent of this project is to provide a useful library to the public for whatever means they see fit. This license will be good for personal and commercial interests.

  • 05/04/06

    Quite a few people have sent in additions and improvements to the code. The most notable is support for active mode FTP sessions. Carlo Andreoli submitted a fully functional implementation of the PORT command for data channels. Many thanks go out to Carlo for this code. Sloan Holliday submitted code for retrieving raw FTP dates as well as a DateTime object on a file residing on a FTP server. While not the primary focus of this article, Daniel Tamajón made improvements to the client that's included with this article. He added in command line support that would be very handy for scripting. For a complete list of changes, please see the ChangeLog.txt file included with the source code. Thanks to everyone who has helped in improving the code! Note: If you haven't already read the Points of Interest section of this document, you should do so before implementing this new code in any project using an older version of the ftplib.cs code.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

jptros

Software Developer

United States United States

Member

Systems Administrator, Network Administrator, Developer

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionIt's a 5 for me Pinmemberpippo pioppo2:06 11 Nov '11  
GeneralMy vote of 5 Pinmemberlou giudice10:59 4 Nov '11  
BugLost Connection in download Pinmemberdgnz7:21 6 Oct '11  
GeneralRe: Lost Connection in download Pinmemberchenandczh16:21 16 Apr '12  
GeneralRe: Lost Connection in download Pinmemberdgnz12:49 27 Apr '12  
QuestionChange Directory the download files Pinmemberdgnz12:30 9 Sep '11  
AnswerRe: Change Directory the download files PinmemberMohammed Aminchar5:00 22 Dec '11  
GeneralRe: Change Directory the download files Pinmemberdgnz12:46 27 Apr '12  
QuestionWhat about carriage returns from Mainframe file PinmemberEric Lynn Anderson5:22 25 Aug '11  
AnswerRe: What about carriage returns from Mainframe file Pinmemberjptros5:31 25 Aug '11  
GeneralRe: What about carriage returns from Mainframe file PinmemberEric Lynn Anderson10:02 30 Aug '11  
Questionwhat aboout uploading Pinmemberjeremiahmurimi5:44 16 Aug '11  
Questiontwo classes PinmemberGhostRider838:54 9 Aug '11  
QuestionHow to get just the name of the File or Directory PinmemberAnLa0610959:15 27 Jun '11  
AnswerRe: great Pinmemberdgnz11:44 9 Sep '11  
GeneralMy vote of 1 Pinmemberastronom95:16 23 Jun '11  
GeneralMy vote of 5 PinmemberColin Wyatt-Goodall21:24 14 Jun '11  
Generalobsoleted PinmemberJamshid Hashimi19:04 19 Mar '11  
GeneralRe: obsoleted Pinmemberjptros9:58 24 Mar '11  
GeneralRe: obsoleted PinmemberBjolivot12313:18 17 Jun '11  
GeneralListFiles fails when... PinmemberNospamAtEmailDotCom22:01 8 Mar '11  
GeneralRe: ListFiles fails when... Pinmemberjptros2:45 9 Mar '11  
GeneralRe: ListFiles fails when... PinmemberNospamAtEmailDotCom21:39 9 Mar '11  
GeneralRe: ListFiles fails when... Pinmemberjptros2:46 10 Mar '11  
GeneralRe: ListFiles fails when... Pinmemberjptros2:54 10 Mar '11  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 5 May 2006
Article Copyright 2005 by jptros
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid