Sunday, December 26, 2010

Simple FTP List Example in C#



I've integrated FTP Listing capabilities into my MobileExec Program (screenshot above).  C# has robust FTP capabilities using FTPWebRequest Classes, check out the simple code below. This uses System.Net and System.Sockets. First declare the class, then the usage is below that for the method. 


public class FTPApp
{
    public string[] GetFileList(string UID, string PWD, string Server)
    {
        string[] downloadFiles;
        StringBuilder result = new StringBuilder();
        FtpWebRequest reqFTP;
        try
        {
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + Server + "/"));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(UID, PWD);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            WebResponse response = reqFTP.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());


            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            reader.Close();
            response.Close();
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            //System.Windows.Forms.MessageBox.Show(ex.Message);
            downloadFiles = null;
            return downloadFiles;
        }
    }
}


//Usage Method Below



public void GetFTPList(string Server, 
        string UID, string PWD)
    {
        Label1.Text = "FTP Listing for <b>" + Server + " </b><br />";
        Label1.Text += "--------------------------------------------------- <br />";
        FTPApp FTPA = new FTPApp();
        string[] FTPFileList;
        FTPFileList = FTPA.GetFileList(UID, PWD, Server);
        foreach (string x in FTPFileList)
        {
            Label1.Text += "<a href='" + "ftp://" + 
                UID + ":" + PWD + "@" +
                Server + "/" + x + "'><img src='images/dl.png'></a>" + x + "<br />";
        }
    }

No comments:

Post a Comment