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

FTP component written with fully managed code

Rate me:
Please Sign up or sign in to vote.
4.78/5 (61 votes)
7 May 20021 min read 851.2K   14.7K   178   251
A .NET FTP component

Recently, I needed to write a program which could automatically download files from an FTP server. Unfortunately the .NET Framework lacks good support for FTP services. Although a few companies have already written libraries which can be used directly, the price is really too high for poor men like me. As a result, I decided to write my own FTP library and here it is.

Disclaimer

This FTP component is an incomplete implementation of my design nor has it been fully tested. Please keep in mind it may contain bugs or even design flaws.

Connect to FTP server

C#
FtpSession session = new FtpSession();
session.Server = "localhost";
session.Port   = 21; //not required if using the default ftp port 21
session.Connect("anonymous", "someone@somewhere.com");

Enum subdirectories and files

C#
/*
* It is possible an incorrect list will be returned.
* In this case, you need to add your own regular expression to 
* interpret the list result (try to find it within ftpdirectory.cs)
*/
FtpDirectory root = session.RootDirectory;
foreach(FtpDirectory d in root.SubDirectories)
    //do something

    foreach(FtpFile f in root.Files)
        //do something

        /*
         * Only CurrentDirectory's item can be legally used.
         * Do not save down FtpDirectory and FtpFile for later use
         * unless you are sure they belongs to CurrentDirectory.
         * Here is some sample may cause problems
         */
        FtpDirectory d1 = session.CurrentDirectory.FindSubdirectory("somesubdir");
        FtpDirectory d2 = session.CurrentDirectory.FindSubdirectory("othersubdir");
        session.CurrentDirectory = d2;
        
        /*
         * Following 2 line will cause problem since CurrentDirectory 
         * is not d1's parent anymore
         */
        foreach(FtpDirectory d in d1) 
            //dosomthing

Change current directory

C#
session.CurrentDirectory = somesubdirectory

Upload file

C#
//Blocking call
session.CurrentDirectory.PutFile("somelocalfile");
    
//Async call using callback
session.CurrentDirectory.BeginPutFile("somelocalfile", +
    new FtpAsyncDelegate(yourcallback);
    
//Async call using event
session.EndPutFile += new FtpFileEventHandler(yourhandler);
session.CurrectDirectory.BeginPutFile("somelocalfile");
        
    //Manually upload the file
    FileInfo fi = new FileInfo(localfilefullpath);
    Stream r = File.OpenRead(fi.FullName);

    // actually will return a FtpOutputDataStream object
    Stream w = session.CurrentDirectory.CreateDataStream(fi.Name); 
    int readed;
    byte[] buff = new byte[4096];
    while((readed=r.Read(buff, 0, 4096) != 0)
	    w.Write(buff, 0, readed);
    /*
    * Must call FtpDataStream.Close().
    * This is because it will try to read the file transfer 
    * result from FTP server.
    */
    w.Close();
    s.Close();

Download file

C#
//Blocking call
session.CurrentDirectory.GetFile("someremotefile");
    
//Async call using callback
session.CurrentDirectory.BeginGetFile("someremotefile", + 
    new FtpAsyncDelegate(yourcallback);
    
//Async call using event
session.EngGetFile += new FtpFileEventHandler(yourhandler);
session.CurrectDirectory.BeginGetFile("someremotefile");

//Manually download a file
Stream r = File.OpenWrite(localfilepath);

    FtpFile remoteFile = session.CurrentDirectory.FindFile(remotefilename);
    Stream w = remoteFile.GetOutputDataStream();
    int readed;
    byte[] buff = new byte[4096];
    while((readed=r.Read(buff, 0, 4096) != 0)
        w.Write(buff, 0, readed);
    /*
    * Must call FtpDataStream.Close().
    * This is because it will try to read the file transfer 
    * result from FTP server.
    */
    w.Close();
    s.Close();

Create a new file in ftp server

C#
//method 1
session.CurrentDirectory.CreateFile(newfilename);
        
//method 2
Stream s = session.CurrentDirectory.CreateFileStream(newfilename);
// do something with s
s.Close();

Delete a file from ftp server

C#
//method 1
session.CurrentDirectory.RemoveFile(remotefilename);
        
//method 2
IFtpItem item = session.CurrentDirectory.FindItem(remotefilename)
if(item != null)
    session.CurrentDirectory.RemoveItem(item);

Delete a subdirectory

C#
//method 1
session.CurrentDirectory.RemoveSubdir(subdirectoryname);

//method 2
IFtpItem item = session.CurrentDirectory.FindItem(sub directoryname)
if(item != null)
    session.CurrentDirectory.RemoveItem(item);

Refresh the content of ftp directory

C#
/*
* If you have saved down some some directory item(subdir or ftpfile).
* They will become invalid after you refresh the directory
*/
FtpFile f = session.CurrentDirectory.FindFile(somefile);
         
// you can not leagally use f anymore after the following line
session.CurrentDirectory.Refresh();

Rename a file or directory

C#
IFtpItem item = session.FindItem(directoryorfile);
if(item != null)
    session.RenameSubitem(item, newname);

Known Limitations

  • No support for active mode
  • No support for proxy server

Updates

  • Removed FileCollection and DirectoryCollection
  • Added support for VB's for each statement
  • VB client can directly access FtpDirectory.Files and FtpDirectory.SubDirectories with for each statement now.

Please send me a email if you find any bugs. Please include at least a description of the bug you have found. It will be nice if a testing program or even a solution is included.

Have fun.

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
Web Developer
Hong Kong Hong Kong
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralScalability issues to be aware of Pin
Timian Heber21-Aug-03 7:30
Timian Heber21-Aug-03 7:30 
GeneralRe: Scalability issues to be aware of Pin
Sergey M31-Aug-03 7:11
Sergey M31-Aug-03 7:11 
GeneralClose Connection Pin
GKFlash12-Aug-03 12:59
GKFlash12-Aug-03 12:59 
GeneralFTP download test Pin
GKFlash12-Aug-03 12:03
GKFlash12-Aug-03 12:03 
GeneralRe: FTP download test Pin
GKFlash12-Aug-03 12:36
GKFlash12-Aug-03 12:36 
GeneralChange remote directory Pin
mbassan30-Jul-03 8:11
mbassan30-Jul-03 8:11 
GeneralRe: Change remote directory Pin
trader999927-Nov-03 8:36
trader999927-Nov-03 8:36 
GeneralRe: Change remote directory Pin
trader999928-Nov-03 2:44
trader999928-Nov-03 2:44 
GeneralDifficulty Parsing Directory Line IIS Pin
mikejoz21-Jul-03 13:24
mikejoz21-Jul-03 13:24 
GeneralRe: Difficulty Parsing Directory Line IIS Pin
trader999927-Nov-03 8:38
trader999927-Nov-03 8:38 
GeneralRe: Difficulty Parsing Directory Line IIS Pin
trader999927-Nov-03 9:33
trader999927-Nov-03 9:33 
GeneralRe: Difficulty Parsing Directory Line IIS Pin
Werdna8-Jun-04 5:44
Werdna8-Jun-04 5:44 
GeneralRe: Difficulty Parsing Directory Line IIS Pin
Jason Simotas18-Feb-04 11:16
Jason Simotas18-Feb-04 11:16 
QuestionHow to use FTP using VC++ Pin
plvarun0220-Jul-03 23:48
plvarun0220-Jul-03 23:48 
GeneralCould you please put the binaries Pin
Réda BOUREBABA7-Jul-03 16:35
Réda BOUREBABA7-Jul-03 16:35 
GeneralRe: Could you please put the binaries Pin
daddybob998-Jul-03 3:33
daddybob998-Jul-03 3:33 
GeneralRe: Could you please put the binaries Pin
Réda BOUREBABA8-Jul-03 4:22
Réda BOUREBABA8-Jul-03 4:22 
QuestionCan't see any files? Pin
cdengler6-Jul-03 13:16
cdengler6-Jul-03 13:16 
AnswerRe: Can't see any files? Pin
daddybob997-Jul-03 9:46
daddybob997-Jul-03 9:46 
Generalcould not connect to remote host Pin
sayeed_233-Jun-03 5:52
sayeed_233-Jun-03 5:52 
General"Batch" download help Pin
Jim Osborne14-May-03 9:06
Jim Osborne14-May-03 9:06 
GeneralFtp Site Parameters & Changing Directory Pin
enjoy_life9-May-03 5:40
enjoy_life9-May-03 5:40 
GeneralRe: Ftp Site Parameters & Changing Directory Pin
nmbvc2-Mar-06 5:21
nmbvc2-Mar-06 5:21 
GeneralHang on finding a file while debuging Pin
Agustín Alcázar15-Apr-03 7:01
Agustín Alcázar15-Apr-03 7:01 
GeneralVisual C++ 6.0 version Pin
ckcheung31-Mar-03 19:57
ckcheung31-Mar-03 19:57 

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.