Click here to Skip to main content
11,643,493 members (76,515 online)
Click here to Skip to main content

FTP component written with fully managed code

, 7 May 2002 639.1K 13.8K 178
Rate this:
Please Sign up or sign in to vote.
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

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

/*
* 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

session.CurrentDirectory = somesubdirectory

Upload file

//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

//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

//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

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

Delete a subdirectory

//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

/*
* 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

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

Share

About the Author

Alex Kwok
Web Developer
Hong Kong Hong Kong
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralIncomplete download Pin
Anonymous2-Feb-05 12:18
sussAnonymous2-Feb-05 12:18 
GeneralTypo in kcommon FTP class Pin
Wyatt Wong31-Jan-05 14:44
memberWyatt Wong31-Jan-05 14:44 
Generalproxy server support Pin
John Makin6-Jan-05 2:12
memberJohn Makin6-Jan-05 2:12 
GeneralAnother free, open-source .NET FTP component Pin
Hans Andersen11-Nov-04 11:45
sussHans Andersen11-Nov-04 11:45 
GeneralRe: Another free, open-source .NET FTP component Pin
[pascal]27-Jul-05 6:17
member[pascal]27-Jul-05 6:17 
GeneralcAse-sEnSItiVe regular expressions Match Pin
ttocek8-Nov-04 9:50
memberttocek8-Nov-04 9:50 
Generalrequired windows application for uploading last modified files/folders from [Windows] to [WEB] Pin
sharad1625-Sep-04 3:22
membersharad1625-Sep-04 3:22 
Generalrequired windows application for uploading last modified files/folders from [Windows] to [WEB] Pin
sharad1625-Sep-04 3:21
membersharad1625-Sep-04 3:21 
GeneralError Occured while working (IMP) Pin
sharad1625-Sep-04 2:47
membersharad1625-Sep-04 2:47 
GeneralRe: Error Occured while working (IMP) Pin
xrogzu17-Dec-04 19:46
memberxrogzu17-Dec-04 19:46 
GeneralWelcome message = No connection Pin
Dylan Thomas16-Sep-04 6:32
memberDylan Thomas16-Sep-04 6:32 
GeneralRe: Welcome message = No connection Pin
Basilevs1-Feb-05 20:15
memberBasilevs1-Feb-05 20:15 
Generalstring -> current.directory Pin
Gabbueno9-Sep-04 10:58
memberGabbueno9-Sep-04 10:58 
GeneralSecure FTP (SFTP) Pin
zadeha31-Aug-04 12:30
memberzadeha31-Aug-04 12:30 
GeneralRe: Secure FTP (SFTP) Pin
striped_striped7-Oct-04 4:51
sussstriped_striped7-Oct-04 4:51 
GeneralRe: Secure FTP (SFTP) Pin
_lee10-Nov-04 21:36
member_lee10-Nov-04 21:36 
Generalremove directory and files... Pin
Gabbueno30-Aug-04 10:43
memberGabbueno30-Aug-04 10:43 
GeneralSimpler, better ... Pin
theguz2-Aug-04 9:28
membertheguz2-Aug-04 9:28 
GeneralLIST hangs occasionally Pin
BKStrelioffPAL25-Jun-04 12:36
memberBKStrelioffPAL25-Jun-04 12:36 
GeneralCreate Directory Pin
Ferdi Rezvan20-May-04 0:37
memberFerdi Rezvan20-May-04 0:37 
GeneralTransfer from one to another. Pin
Harinya12-May-04 6:15
memberHarinya12-May-04 6:15 
GeneralThanks Pin
MTSkull30-Apr-04 10:46
memberMTSkull30-Apr-04 10:46 
GeneralRe: Thanks Pin
Anonymous27-Jul-04 7:17
sussAnonymous27-Jul-04 7:17 
QuestionLatest version? Pin
Nathan Ridley29-Apr-04 19:08
memberNathan Ridley29-Apr-04 19:08 
GeneralMatchingListLine still a problem Pin
Great Milenko26-Apr-04 4:33
memberGreat Milenko26-Apr-04 4:33 
GeneralRe: MatchingListLine still a problem Pin
phaser27-Apr-04 21:37
sussphaser27-Apr-04 21:37 
GeneralCan't see any Files in the Current Directory Pin
steque26-Mar-04 2:51
membersteque26-Mar-04 2:51 
GeneralRe: Can't see any Files in the Current Directory Pin
Bee126-Aug-04 3:29
memberBee126-Aug-04 3:29 
GeneralSubDirectories Pin
runeks24-Mar-04 22:51
memberruneks24-Mar-04 22:51 
GeneralRe: SubDirectories Pin
SpamMePleaseCS19-Sep-05 16:17
memberSpamMePleaseCS19-Sep-05 16:17 
Generalfile upload without user interaction Pin
Anonymous22-Mar-04 22:04
sussAnonymous22-Mar-04 22:04 
GeneralRe: file upload without user interaction Pin
ttocek8-Nov-04 4:21
memberttocek8-Nov-04 4:21 
GeneralArithmetic operation resulted in an overflow Pin
testmalar23-Feb-04 18:04
susstestmalar23-Feb-04 18:04 
GeneralCopy/rename files Pin
christina gustafsson18-Feb-04 20:33
memberchristina gustafsson18-Feb-04 20:33 
GeneralAn alternative to all this Pin
jgarrison6112-Feb-04 7:42
memberjgarrison6112-Feb-04 7:42 
GeneralRe: An alternative to all this Pin
tgvolk16-Feb-04 6:13
membertgvolk16-Feb-04 6:13 
Generalcannot list files and subdirectories Pin
Anonymous24-Dec-03 3:00
sussAnonymous24-Dec-03 3:00 
GeneralRemoveFile may throw NullReferenceException Pin
theguz23-Dec-03 3:39
membertheguz23-Dec-03 3:39 
GeneralDoesn't work on OpenVMS Pin
Anonymous5-Dec-03 3:54
sussAnonymous5-Dec-03 3:54 
GeneralCreate Directory Pin
Andrew Jones9-Oct-03 4:16
memberAndrew Jones9-Oct-03 4:16 
GeneralRe: Create Directory Pin
Jitesh Sinha11-Oct-03 3:55
memberJitesh Sinha11-Oct-03 3:55 
GeneralChangeDirectory Method Pin
jim@bitxbit.com2-Sep-03 9:10
memberjim@bitxbit.com2-Sep-03 9:10 
GeneralRe: ChangeDirectory Method Pin
didg19-May-04 13:02
memberdidg19-May-04 13:02 
GeneralAutoUpdate an VB.net application from an FTP serverf Pin
Dino6825-Aug-03 9:19
memberDino6825-Aug-03 9:19 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
Virender Sandhu25-Aug-03 10:11
memberVirender Sandhu25-Aug-03 10:11 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
dinoMB6825-Aug-03 11:02
memberdinoMB6825-Aug-03 11:02 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
dinoMB6825-Aug-03 11:34
memberdinoMB6825-Aug-03 11:34 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
joan_fl25-Aug-03 10:36
memberjoan_fl25-Aug-03 10:36 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
dinoMB6825-Aug-03 11:05
memberdinoMB6825-Aug-03 11:05 
GeneralRe: AutoUpdate an VB.net application from an FTP serverf Pin
Virender Sandhu25-Aug-03 13:46
memberVirender Sandhu25-Aug-03 13:46 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150731.1 | Last Updated 8 May 2002
Article Copyright 2002 by Alex Kwok
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid