5,422,921 members and growing! (17,745 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate

FTP component written with fully managed code

By Alex Kwok

A .NET FTP component
C#, Windows, .NET 1.0, .NETVisual Studio, VS.NET2002, Dev

Posted: 7 May 2002
Updated: 7 May 2002
Views: 324,944
Bookmarked: 135 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
70 votes for this Article.
Popularity: 7.87 Rating: 4.27 out of 5
7 votes, 12.3%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
12 votes, 21.1%
4
38 votes, 66.7%
5

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

About the Author

Alex Kwok



Occupation: Web Developer
Location: Hong Kong Hong Kong

Other popular .NET Framework 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 232 (Total in Forum: 232) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralA comfortable FTP class in .NETmemberElmue21hrs 41mins ago 
GeneralHow can i connect to xxx.xxx.xxx.xxx\someFolder?memberipop007zZZ0:10 7 Jul '08  
GeneralHow create directorymemberalien2503:23 11 Sep '07  
GeneralRe: How create directorymemberalien2504:17 11 Sep '07  
GeneralParent DirectorymemberLava041:24 13 Jun '07  
GeneralHow to move a file from one directory to another directory in ftpmemberchandu.sanka3:17 28 Nov '06  
Questionhow to trace the target location directorymemberchandu.sanka3:13 28 Nov '06  
Questionkcommon.dllmember_anagram_3:32 1 Nov '06  
AnswerRe: kcommon.dllmember_anagram_7:12 1 Nov '06  
GeneralHow to download from ftp server using VS2003memberRaju Sharma21:21 17 Oct '06  
Generalftp uploadmemberpreets30821:15 16 Jul '06  
GeneralCoping file to different directory in remote servermemberjasocl23:11 3 Jul '06  
AnswerRe: Coping file to different directory in remote servermemberstixoffire6:18 10 Apr '08  
GeneralUNIX regex's not recognising all files returned by LIST command - fix supplied here!!memberStewart Rae16:58 8 May '06  
GeneralRe: UNIX regex's not recognising all files returned by LIST command - fix supplied here!!memberShorin_gr5:14 15 Jun '06  
GeneralRe: UNIX regex's not recognising all files returned by LIST command - fix supplied here!!memberAquaJo10:14 13 Jul '06  
GeneralCannot connect .. Help !!memberStar999918:18 19 Apr '06  
GeneralSubdirectorymembernmbvc6:01 2 Mar '06  
Generalcan't download demo file?sussAnonymous14:39 6 Oct '05  
GeneralHi Alexmembersantosh poojari21:40 14 Sep '05  
GeneralHelp!! Problem Kcommon GetFilememberJugkrit_Emp@hotmail.com22:07 22 Aug '05  
GeneralRe: Help!! Problem Kcommon GetFilesussAnonymous1:58 29 Aug '05  
Generalavoid blocking while reading response stream!member[pascal]5:59 17 Aug '05  
GeneralRe: avoid blocking while reading response stream!membercphexad4:44 13 Feb '07  
GeneralHi Help neededmemberNR_gopal2:40 3 Aug '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 May 2002
Editor: Paul Watson
Copyright 2002 by Alex Kwok
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project