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

LightFTPClient: a basic FTP client

Rate me:
Please Sign up or sign in to vote.
4.39/5 (11 votes)
9 May 2004CPOL1 min read 160.5K   2.3K   48   53
LightFTPClient is a basic FTP client.

Introduction

This is a simple FTP client written in C#.

Usage

LightFTPClient is a basic FTP client. To implement FTP communication, I adapted the FTP client library of Jaimon Mathew.

LightFTPClient maintains data (username, password, port) of your connections in a list, so you can select one directly from the list. These data will be persisted into a file named lightftpclient.bin. This file will be created in the same directory where the executable is located. Data is saved when the program is closed.

Sample screenshot

System and error messages are shown in the middle area. At the bottom, on the left, there is the local path and its contents, on the right there is the remote path and its contents.

The following function is invoked to populate list referring local path.

C#
protected void PopulateLocalFileList()
{
    //Populate listview with files
    string[] lvData =  new string[4];
    string sPath = txtLocalPath.Text;

    InitListView(lvLocalFiles);

    if (sPath.Length > 3)
        addParentDirectory(lvLocalFiles);
    else
    {

    }
    try
    {
        string[] stringDir = Directory.GetDirectories(sPath);
        string[] stringFiles = Directory.GetFiles(sPath);

        string stringFileName = "";
        DateTime dtCreateDate, dtModifyDate;
        Int64 lFileSize = 0;

        foreach (string stringFile in stringDir)
        {
            stringFileName = stringFile;
            FileInfo objFileSize = new FileInfo(stringFileName);
            lFileSize = 0;
            dtCreateDate = objFileSize.CreationTime;
                        dtModifyDate = objFileSize.LastWriteTime; 

            //create listview data
            lvData[0] = "";
            lvData[1] = GetPathName(stringFileName);
            lvData[2] = formatSize(lFileSize);
            lvData[3] = formatDate(dtModifyDate);

            //Create actual list item
            ListViewItem lvItem = new ListViewItem(lvData,0); // 0 = directory
            lvLocalFiles.Items.Add(lvItem);

        }

        foreach (string stringFile in stringFiles)
        {
            stringFileName = stringFile;
            FileInfo objFileSize = new FileInfo(stringFileName);
            lFileSize = objFileSize.Length;
            dtCreateDate = objFileSize.CreationTime; 
                        dtModifyDate = objFileSize.LastWriteTime; 

            //create listview data
            lvData[0] = "";
            lvData[1] = GetPathName(stringFileName);
            lvData[2] = formatSize(lFileSize);
            lvData[3] = formatDate(dtModifyDate);

            //Create actual list item
            ListViewItem lvItem = new ListViewItem(lvData,1); // 1 = file
            lvLocalFiles.Items.Add(lvItem);

        }

        // Loop through and size each column header
        // to fit the column header text.
        foreach (ColumnHeader ch in this.lvLocalFiles.Columns)
        {
            ch.Width = -2;
        }

    }
    catch (IOException)
    {
        MessageBox.Show("Error: Drive not ready or directory does not exist.");
    }
    catch (UnauthorizedAccessException)
    {
        MessageBox.Show("Error: Drive or directory access denided.");
    }
    catch (Exception ee)
    {
        MessageBox.Show("Error: " + ee);
    }
    lvLocalFiles.Invalidate();
    lvLocalFiles.Update();

}

Clicking on the header "Name", you can sort file list. To sort the file list, I make an implementation of the IComparer interface.

C#
public class ListViewColumnSorter : IComparer
{
    /// <SUMMARY>
    /// Specifies the column to be sorted
    /// </SUMMARY>
    private int ColumnToSort;
    /// <SUMMARY>
    /// Specifies the order in which to sort (i.e. 'Ascending').
    /// </SUMMARY>
    private SortOrder OrderOfSort;
    /// <SUMMARY>
    /// Case insensitive comparer object
    /// </SUMMARY>
    private CaseInsensitiveComparer ObjectCompare;

    /// <SUMMARY>
    /// Class constructor.  Initializes various elements
    /// </SUMMARY>
    public ListViewColumnSorter()
    {
        // Initialize the column to '1'
        ColumnToSort = 1;

        // Initialize the sort order to 'Ascending'
        OrderOfSort = SortOrder.Ascending;

        // Initialize the CaseInsensitiveComparer object
        ObjectCompare = new CaseInsensitiveComparer();
    }

    /// <SUMMARY>
    /// This method is inherited from the IComparer interface.  
    /// It compares the two objects passed using
    /// a case insensitive comparison.
    /// 
    /// Comparison rules: 
    /// - directories are listed before (ascending)
    ///           or after (descending) than files;
    /// - both directories both files are listed
    ///           in ascending or descending order.
    /// </SUMMARY>
    /// <PARAM name="x">First object to be compared</PARAM>
    /// <PARAM name="y">Second object to be compared</PARAM>
    /// <RETURNS>The result of the comparison. "0" if equal,
    /// negative if 'x' is less than 'y' and positive
    /// if 'x' is greater than 'y'</RETURNS>
    public int Compare(object x, object y)
    {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // Cast the objects to be compared to ListViewItem objects
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        if ( (listviewX.ImageIndex == listviewY.ImageIndex) 
          ||  ((listviewX.ImageIndex +listviewY.ImageIndex) == 2) )
        {
            // items are of the same type (2 directory or 2 files)
            // with a tirck (listviewX.ImageIndex +listviewY.ImageIndex)
            // one is a link, one is a dir
            // Compare the two items
            compareResult = 
              ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,
              listviewY.SubItems[ColumnToSort].Text);
        }
        else
        {
            // items are of different type
            // directory are listed before (ascending order) than files
            // or after (descending order) than files
            // Note: in my FTP client
            // ImageIndex = 0 means that item is a directory
            // ImageIndex = 1 means that item is a file
            // ImageIndex = 2 means that item is a link
            compareResult = 
              ((listviewX.ImageIndex < listviewY.ImageIndex)?-1:1);
        }

        // Calculate correct return value based on object comparison
        if (OrderOfSort == SortOrder.Ascending)
        {
            // Ascending sort is selected, return normal
            // result of compare operation
            return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending)
        {
            // Descending sort is selected,
            // return negative result of compare operation
            return (-compareResult);
        }
        else
        {
            // Return '0' to indicate they are equal
            return 0;
        }
    }
    
    /// <SUMMARY>
    /// Gets or sets the number of the column to which
    /// to apply the sorting operation (Defaults to '0').
    /// </SUMMARY>
    public int SortColumn
    {
        set
        {
            ColumnToSort = value;
        }
        get
        {
            return ColumnToSort;
        }
    }

    /// <SUMMARY>
    /// Gets or sets the order of sorting to apply
    /// (for example, 'Ascending' or 'Descending').
    /// </SUMMARY>
    public SortOrder Order
    {
        set
        {
            OrderOfSort = value;
        }
        get
        {
            return OrderOfSort;
        }
    }
}

And I assigned it to the ListView.

C#
.....
// Create an instance of a ListView column sorter and assign it 
// to ListView control.
lvwColumnSorter = new ListViewColumnSorter();
this.lvFiles.ListViewItemSorter = lvwColumnSorter;

lvwLocalColumnSorter = new ListViewColumnSorter();
this.lvLocalFiles.ListViewItemSorter = lvwLocalColumnSorter;
.....

To navigate, use mouse or type path in the respective input box, then type "Enter".

Use drag & drop to download or upload a file, and the context menu to rename/delete it or to refresh content (it's also possible to use function key).

Sample screenshot

System Requirements

This application was developed using VS.NET/C# and Microsoft .NET Framework 1.1, and tested on Win 2000.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Error return : invalid response for PASV command Pin
seb.491-Mar-06 3:37
seb.491-Mar-06 3:37 
AnswerRe: Error return : invalid response for PASV command Pin
Massimo Beatini1-Mar-06 4:15
Massimo Beatini1-Mar-06 4:15 
GeneralRe: Error return : invalid response for PASV command Pin
seb.491-Mar-06 4:18
seb.491-Mar-06 4:18 
AnswerRe: Error return : invalid response for PASV command Pin
Massimo Beatini1-Mar-06 5:01
Massimo Beatini1-Mar-06 5:01 
GeneralRe: Error return : invalid response for PASV command Pin
maximus.dec.meridius8-Sep-09 8:55
maximus.dec.meridius8-Sep-09 8:55 
GeneralBinary or Ascii Pin
jpazgier30-Aug-05 8:00
jpazgier30-Aug-05 8:00 
AnswerRe: Binary or Ascii Pin
Massimo Beatini31-Aug-05 1:18
Massimo Beatini31-Aug-05 1:18 
GeneralHelp Me Please Pin
codeajay8-Mar-05 20:18
codeajay8-Mar-05 20:18 
Questionpassive or active ? Pin
Gabbueno8-Mar-05 3:29
Gabbueno8-Mar-05 3:29 
AnswerRe: passive or active ? Pin
mbeatini8-Mar-05 3:51
sussmbeatini8-Mar-05 3:51 
QuestionDo i need any license to use your code? Pin
Indian Ocean20-Feb-05 19:04
Indian Ocean20-Feb-05 19:04 
AnswerRe: Do i need any license to use your code? Pin
mbeatini20-Feb-05 21:06
sussmbeatini20-Feb-05 21:06 
Questionbroken pipe? Pin
yomomma121-Dec-04 12:11
yomomma121-Dec-04 12:11 
AnswerRe: broken pipe? Pin
mbeatini21-Dec-04 23:50
sussmbeatini21-Dec-04 23:50 
GeneralRe: broken pipe? Pin
yomomma122-Dec-04 10:03
yomomma122-Dec-04 10:03 
AnswerRe: broken pipe? Pin
Tom Willett8-Dec-05 9:05
Tom Willett8-Dec-05 9:05 
AnswerRe: broken pipe? Pin
Massimo Beatini10-Dec-05 13:11
Massimo Beatini10-Dec-05 13:11 
GeneralAnother free, open-source .NET FTP component Pin
h_c_a_andersen11-Nov-04 12:03
h_c_a_andersen11-Nov-04 12:03 
Generalthread.sleep(700) Pin
Gabbueno5-Nov-04 2:15
Gabbueno5-Nov-04 2:15 
GeneralRe: thread.sleep(700) Pin
Massimo Beatini5-Nov-04 3:12
Massimo Beatini5-Nov-04 3:12 
QuestionWrong warning message? Pin
Member 35331230-Oct-04 0:51
Member 35331230-Oct-04 0:51 
AnswerRe: Wrong warning message? Pin
mbeatini1-Nov-04 5:54
sussmbeatini1-Nov-04 5:54 
Questionhow to add quota limits to a user using .net interface Pin
Member 113378520-Jun-04 21:26
Member 113378520-Jun-04 21:26 
Questionbug? Pin
wiseleyb2-Jun-04 4:33
wiseleyb2-Jun-04 4:33 
AnswerRe: bug? Pin
mbeatini8-Jun-04 5:09
sussmbeatini8-Jun-04 5:09 

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.