5,427,813 members and growing! (17,457 online)
Email Password   helpLost your password?
General Programming » Internet / Network » FTP     Intermediate License: A Public Domain dedication

C# FTP Client Library

By J.P. Trosclair

Easy to use FTP client library with features in mind.
C#.NET 1.1, WinXP, Windows, .NETVisual Studio, VS.NET2003, Dev

Posted: 11 Jul 2005
Updated: 5 May 2006
Views: 187,729
Bookmarked: 142 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
51 votes for this Article.
Popularity: 7.77 Rating: 4.55 out of 5
1 vote, 2.0%
1
1 vote, 2.0%
2
3 votes, 6.0%
3
13 votes, 26.0%
4
32 votes, 64.0%
5

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

J.P. Trosclair


I work for a small company writing software and I've been in college too long, but I'll be done one day! Smile
Occupation: Software Developer
Location: United States United States

Other popular Internet / Network articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 238 (Total in Forum: 238) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralA comfortable FTP class in .NETmemberElmue13:16 27 Aug '08  
GeneralWhy not use the standard libraries?memberPeter Hendrix0:28 19 Aug '08  
GeneralRe: Why not use the standard libraries?memberJ.P. Trosclair2:27 19 Aug '08  
GeneralRe: Why not use the standard libraries?memberPeter Hendrix2:42 19 Aug '08  
GeneralRe: Why not use the standard libraries?memberMarco Mastropaolo12:58 20 Aug '08  
GeneralError in Aborting..memberBalamurugan R A7:43 5 Jun '08  
QuestionTimeout when downloading large filesmemberstreit4:48 28 May '08  
GeneralUpload buffer sizememberSanek6:42 22 May '08  
GeneralFTP client librarymemberxaml.net0:16 22 May '08  
General550 OPERATION NOT COMPLETE AT FTPLIB.FTP.GETFILESIZE(STRING FILENAME)memberFrankie_3:48 21 May '08  
GeneralRe: 550 OPERATION NOT COMPLETE AT FTPLIB.FTP.GETFILESIZE(STRING FILENAME)memberJ.P. Trosclair11:18 21 May '08  
GeneralRe: 550 OPERATION NOT COMPLETE AT FTPLIB.FTP.GETFILESIZE(STRING FILENAME)memberFrankie_3:28 22 May '08  
GeneralRe: 550 OPERATION NOT COMPLETE AT FTPLIB.FTP.GETFILESIZE(STRING FILENAME)memberJ.P. Trosclair3:34 22 May '08  
QuestionOdd IssuesmemberMember 12694737:22 19 May '08  
AnswerRe: Odd IssuesmemberJ.P. Trosclair7:37 19 May '08  
GeneralRe: Odd IssuesmemberMember 12694738:39 19 May '08  
GeneralRe: Odd IssuesmemberJ.P. Trosclair8:46 19 May '08  
QuestionRe: Odd IssuesmemberMember 126947311:16 19 May '08  
QuestionBug in DoUpload ??memberLiang-Kuan Hu0:53 16 May '08  
AnswerRe: Bug in DoUpload ??memberJ.P. Trosclair4:39 16 May '08  
GeneralRe: Bug in DoUpload ??memberLiang-Kuan Hu17:51 17 May '08  
GeneralRe: Bug in DoUpload ??memberJ.P. Trosclair20:09 17 May '08  
GeneralFile name prohibitedmemberFernan212:14 14 May '08  
GeneralRe: File name prohibitedmemberJ.P. Trosclair12:23 14 May '08  
GeneralRe: File name prohibitedmemberJ.P. Trosclair12:26 14 May '08  

General General