Build an FTP Program in C Sharp

We’re going to build a bare-bones FTP client you can use to upload and download files from your server. If you’ve never programmed in C# before, or have never done any network or FTP programming, this project will serve as a tutorial.

The specifications

Our example program doesn’t have a GUI, just raw functionality. It’s got three functions: Upload a file to a server, download a file from a server, and list the files in a server directory, given the URL to that directory.

How to build it

To build this project you’ll need C# 2008 or later. The Express edition will work fine. Download it from the Visual C# Express link in this article’s Resources section.

Once you’ve installed the C# IDE, open it up and create a new project called “MyFtp.” Paste over the default source code with this article’s code, then enter your own login and password info in the statement that begins with “new NetworkCredential(“YOUR-FTP-LOGIN”…

BE CAREFUL: hardcoding your login and password is NOT a good idea in terms of security. We’re doing so in this sample project only to keep the code small, legible, and easy to use. Adapt the program to accept the login/password from the command line or other secure source.

After you’ve added your login credentials, build the executable by pressing F6.

Executing it

Let’s navigate to the executable. A practical way of finding its folder is to do the following: inside the C# IDE, select “Save as” — but don’t press return; just copy the full path of the project to the Clipboard, minus the filename, then paste that path into the address bar of Windows Explorer.

For example, from this full path:

"C:UsersdskDesktopC++MyFtpMyFtpMyFtpProgram.cs"

Copy just this much to the Clipboard, then to the address bar of Windows Explorer:

C:UsersdskDesktopC++MyFtpMyFtpMyFtp

Open a command prompt

Inside Windows Explorer we still need to drill down to the binRelease subfolder. Open a command prompt in that folder. (See Tips later in this article if you’re not sure how to do this.)

Type the executable’s name: “MyFtp.” The program will display the usage menu since we gave it no arguments.

Let’s try the list directory command: type “MyFtp /L “. The program will return a listing of all files and subfolders within the folder you specify.

Upload files

Try a file upload: type “MyFtp”, followed by these, all on the same command line: the name of a file in the same folder as the MyFtp executable, followed by the URL of the server folder to receive the file.

After you press enter, the file will be uploaded–which you can verify by running MyFtp with the “/L” directory-listing option given previously.

Download files

Fetch files from your server by entering these on a command line:

MyFtp

The application will download the server’s file to the folder you’re running MyFtp from.

The essentials of the program

The NET classes used by MyFtp make the FTP tasks extremely straightforward. For example, all you need to download a file is this code:

- WebClient webClient = new WebClient(); // Create the webclient

- webClient.Credentials = creds; // Submit your login id and password

- webClient.DownloadFile(..); // Download the file

The UploadFile function is nearly the same as DownloadFile, so let’s look instead at the barebones code for the ListDirectory function, which is a bit more involved:

// Create the request object:

... listRequest = ... WebRequest.Create(...);

// Submit login and password:

listRequest.Credentials = creds;

// Specify the "List Directory" command:

listRequest.Method = ... .Ftp.ListDirectoryDetails;

// Send the request to the server

serverResponse = ... listRequest.GetResponse();

// Create a reader to catch the server's response

strmReader = new StreamReader(serverResponse...)

// Print what the reader is reading:

Console.WriteLine(strmReader.ReadToEnd());

The rest of the program

The remaining code preps the objects and parameters for those statements, processes their output, or handles potential errors (e.g. try-catch blocks).

The meaning of each statement is pretty clear, largely because the NET Classes and their methods are pretty clear. It’s not easy to misinterpret what the WebClient.UploadFile method does, for example.

But, understanding the code isn’t _knowing_ it and being able to program with it. To do those, tinker with the code, and even try to memorize it, function by function.

#region Using directives
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
#endregion

static class Program
{
    private static void Main(string[] args)
    {
        NetworkCredential creds =
            new NetworkCredential("YOUR-FTP-LOGIN",
            "YOUR-FTP-PASSWORD");
        if (args.Length == 0)
        {
            showUsage();
            return;
        }
        try
        {
            if (args.Length == 2 && args[0].ToLower() == "/l")
            {
                ListDirectory(args[1], creds);
                return;
            }
            if (args.Length == 2)
            {
                UploadFile(args[0], args[1], creds);
                return;
            }
            DownloadFile(args[0], creds);

        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message);
        }

    } //main

    private static void showUsage()
    {
        string s1 = "Upload: MyFtp <client side file>, ";
        s1 += "<server address to upload to>";
        Console.WriteLine(s1);
        s1 = "List dir: MyFtp /l < server address ";
        s1 += "to get directory listing for>";
        Console.WriteLine(s1);
        s1 = "Download: MyFtp <server address: a file ";
        s1 += "to dl to current directory on client>";
        Console.WriteLine(s1);
    }

    private static void DownloadFile(string downloadAddress,
        NetworkCredential creds)
    {
        WebClient webClient = new WebClient();
        webClient.Credentials = creds;
        //Pull off the filename. w/ a regular expression
        string fileName = "";
        Regex r = new Regex(@"/[^/]+$");
        Match m = r.Match(downloadAddress);
        fileName = m.ToString();
        fileName = fileName.Substring(1, fileName.Length - 1);
        webClient.DownloadFile(downloadAddress, fileName);
        webClient.Dispose();
    }

    private static void UploadFile(string sSourceFile,
        string sDest, NetworkCredential creds)
    {
        WebClient webClient = new WebClient();
        webClient.Credentials = creds;
        string sFullDest = sDest + "/" + sSourceFile;
        webClient.UploadFile(sFullDest, sSourceFile);
        webClient.Dispose();
    }

    private static void ListDirectory(string serverFolderURL,
        NetworkCredential creds)
    {
        StreamReader strmReader = null;
        FtpWebRequest listRequest =
            (FtpWebRequest)WebRequest.Create(serverFolderURL);
        listRequest.Credentials = creds;
        listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        FtpWebResponse serverResponse =
                (FtpWebResponse)listRequest.GetResponse();
        strmReader = new StreamReader(serverResponse.GetResponseStream());
        Console.WriteLine(strmReader.ReadToEnd());
        if (strmReader != null)
            strmReader.Close();
    }
}

Tips

Here are some tips to make navigating to the executable’s folder at the command prompt as painless as possible:

If you have Vista, you can press Shift and right-click on a folder in the right pane of Windows Explorer, then select “Open Command Window Here.”

For other Windows versions, you can easily add the same command window tool by following the steps in this article.

References

The FtpWebRequest Class on MSDN

Resources

Visual C# 2008 Express Edition

4 Comments on "Build an FTP Program in C Sharp"

  1. Will says:

    This looks interesting, I will give this a go later on.

    Nice article.

  2. Travis says:

    Try formatting your code in a readable style…

  3. Scott says:

    There are so many images on the Web. How can you know whether an image is original or has been edited by Photoshop? Check it out using Photoshopped Image Killer. Specify your image’s URL and the site will do analysis for you automatically.

Got something to say? Go for it!