Click here to Skip to main content
Licence 
First Posted 29 May 2002
Views 239,427
Bookmarked 97 times

FTP Component in C#, for .NET

By | 29 May 2002 | Article
An FTP component and sample FTP client, in C#.

Introduction

For my first experience writing a C# component I decided to implement an FTP Component. This is the sample code to use the component. The component code is not really guaranteed to work fine in this state, but I thought that it might be of some interest and that feedback will help to improve or correct features.

Simply add the component to the ToolBox (Using customize Toolbox) and put it on your form. The code project contains a simple FTP Client. You may have to change FTPCom Reference in TestFTPCom project to test the sample. Remove the old reference and Add Reference to FtpCom.DLL

Sample Code

Connect to the FTP Server

ftpc.Username = EFUsername.Text;
ftpc.Password = EFPassword.Text;

ftpc.Hostname = CBFTPServer.Text;
ftpc.Connect();

Logging in to the server

When the connection is completed, the object receives the event Connected, you can then send the Login Command.

private void ftpc_Connected(object sender, FTPCom.FTPEventArgs e)
{
    ftpc.Login();
}

The event Logged is sent after successful connection

private void ftpc_Logged(object sender, FTPCom.FTPEventArgs e)
{
    ftpc.Dir();
}

Getting a directory listing

The DirCompleted event is received when Dir command is completed FileCount contains the number of files, use IsFolder to find if File is a folder. GetFileName and GetFileSize return the name and the size of the files

Note : File Collection is not implemented in this version as it should be!

private void ftpc_DirCompleted(object sender, FTPCom.FTPEventArgs e)
{
    int i = 0;
    int idimage = 0;
    string msg;

    msg = "Transfered " + e.TotalBytes.ToString() + " bytes in " + 
          ((float)e.TimeElapsed / 1000).ToString() + " seconds" + CRLF; 
    TextLog.SelectionColor = Color.Black;
    TextLog.AppendText(msg);

    ServerView.BeginUpdate();
    ServerView.Items.Clear();
    ImgListServerSmall.Images.Clear();

    ListViewItem lvItem = new ListViewItem("..");
    ServerView.Items.Add(lvItem);

    for (i = 0; i < ftpc.FileCount; i++)
    {
        if (ftpc.IsFolder(i))
        {
            string[] items = new String[2];
            items[0] = ftpc.GetFileName(i);
            items[1] = ftpc.GetFileSize(i).ToString();
            ImgListServerSmall.Images.Add (m_IconFolder);
            ServerView.Items.Add(new ListViewItem(items, idimage++));
        }
    }
    for (i = 0; i < ftpc.FileCount; i++)
    {
        if (!ftpc.IsFolder(i))
        {
            string[] items = new String[2];
            items[0] = ftpc.GetFileName(i);
            items[1] = ftpc.GetFileSize(i).ToString();
            ImgListServerSmall.Images.Add (ExtractIcon.GetIcon(items[0], false));
            ServerView.Items.Add(new ListViewItem(items, idimage++));
        }
    }
    ServerView.EndUpdate();
    this.Cursor = Cursors.Default;
}

Downloading a file

File Download on Local View drag drop

private void ServerView_MouseMove(object sender, 
                                  System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button != 0)
    {
        string msg = "";

        for (int i = 0; i < ServerView.SelectedItems.Count; i++)
        {
            msg += ServerView.SelectedItems[i].Text + "\n";
        }

        ServerView.DoDragDrop(msg, DragDropEffects.Copy | DragDropEffects.Move);
    }
}

private void LocalView_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.Text)) 
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

private void LocalView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
    string msg = e.Data.GetData(DataFormats.Text).ToString();

    string[] filename = msg.Split(new char[] { '\n' });
    foreach (string sfile in filename)
    {
        ftpc.FileDownload(sfile);
    }
}

When downloading a file is complete the FileDownloadCompleted event is fired

private void ftpc_FileDownloadCompleted(object sender, FTPCom.FTPEventArgs e)
{
    string msg = "Transfered " + e.TotalBytes.ToString() + " bytes in " + 
                 ((float)e.TimeElapsed / 1000).ToString() + " seconds" + CRLF; 
    TextLog.SelectionColor = Color.Black;
    TextLog.AppendText(msg);
    FillLocalView(m_currentFolder);
}

Deleting selected files

for (int i = 0; i < ServerView.SelectedItems.Count; i++)
{
    ftpc.Delete (ServerView.SelectedItems[i].Text);
}
ftpc.Dir();

Rename a file

private void ServerView_AfterLabelEdit(object sender, 
                         System.Windows.Forms.LabelEditEventArgs e)
{
    if (e.Label != null)
    {
        this.Cursor = Cursors.WaitCursor;

        string newfilename = e.Label;
        if (m_previousfilename == "New Folder")
        {
            ftpc.DirCreate(newfilename);
        }
        else
        {
            ftpc.Rename(m_previousfilename, newfilename);
        }
        ftpc.Dir();
    }
}

Close the connection

ftpc.Disconnect();
ServerView.Items.Clear();

Hope this help. Any comments are welcome.

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

Jerome Lacaille



France France

Member



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
GeneralFTP Commponent Pinmembercndy1985010623:41 19 Apr '09  
GeneralRe: FTP Commponent Pinmembercwvdavid8:38 26 Sep '09  
GeneralCool PinmemberAxonn Echysttas13:50 12 Mar '09  
GeneralA comfortable FTP class in .NET PinmemberElmue12:18 27 Aug '08  
Questionftp folder download PinmemberMember 471155723:13 9 Apr '08  
GeneralNot listing the remote directory contents completely PinmemberMathachanJK19:10 28 Nov '06  
QuestionRe: Not listing the remote directory contents completely PinmemberMember 471155723:30 9 Apr '08  
QuestionDownloading FTP Folder [modified] Pinmembershafqatmasood19:37 9 Aug '06  
AnswerRe: Downloading FTP Folder Pinmembershafqatmasood22:19 10 Aug '06  
QuestionRe: Downloading FTP Folder PinmemberMember 471155722:56 9 Apr '08  
GeneralREMOVE / UPLOAD DIRECTOR WITH SUB DIRECTOR Pinmemberraznalove2:37 1 Jul '06  
GeneralCode does not work Pinmembermbde2:32 23 Mar '06  
GeneralFTP events in c# PinmemberCRASH720:04 6 Dec '05  
Generalnot all data Pinmemberdrxy20:30 13 Feb '05  
GeneralJaimon's FTP Client library may help PinmemberCasp5:54 14 Dec '04  
GeneralNon-Compatibility bug with Sun PinsussAnonymous3:09 24 Nov '04  
GeneralRe: Non-Compatibility bug with Sun PinmembermrBussy4:44 1 Aug '05  
GeneralAnother free, open-source .NET FTP component PinsussHans Andersen12:15 10 Nov '04  
GeneralRe: Another free, open-source .NET FTP component Pinmemberzini10:43 3 Mar '06  
GeneralRe: Another free, open-source .NET FTP component [modified] Pinmemberh_c_a_andersen16:45 12 Dec '06  
GeneralWrong in the GetIcon(string strPath, bool bSmall) method Pinmemberande_vega12:01 20 Oct '04  
GeneralTwo question PinmemberCliniC2:19 16 Aug '04  
GeneralInput fail -> freeze PinmemberCliniC22:49 5 Jun '04  
QuestionHow to use it in background? PinmemberJackfan21:45 23 Mar '04  
AnswerRe: How to use it in background? Pinmemberbyshome20:30 15 Sep '05  

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
Web01 | 2.5.120517.1 | Last Updated 30 May 2002
Article Copyright 2002 by Jerome Lacaille
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid