Demonstration of Client FTP

Introduction

In my previous article, I talked about FTP local hosting and now I'm explaining further how to implement FTP in a C# application. In this tutorial, I will play with a FTP class.

In brief, we create a FTP connection then start exploring the Directory list, then download a file from or upload a file to the FTP server.



Background

In background, you need a FTP host, either locally or remotely. So, you have a host name, a user name and a word of that. It is good if you know the port number of your host (port 21 is the default for FTP).

Procedure

Step 1

Start a Console Project in C# and create a new class inside the same namespace.

I have named it FtpClient { … }.

Within that, we have three private fields of string type.

        string _hostName;

        string _userName;

        string _word;

And, for their value assignment we have constructed a three argument constructor.

public FtpClient(string hostName, string username, string word)

{

    _hostName = hostName;

    _userName = username;

    _word = word;

}

Now, we will try to list all the directories / files in the FTP host.

In C# code, it will look like:

public List<string> DirectoryListing()

{

    // Sent Request

    FtpWebRequest request =(FtpWebRequestWebRequest.Create(_hostName);

    //Specify the resuest Type

    request.Method = WebRequestMethods.Ftp.ListDirectory;

    //Set Username and word

    request.Credentials = new NetworkCredential(_userName, _word);

     FtpWebResponse response = (FtpWebResponse)request.GetResponse();

     Stream responseStream = response.GetResponseStream();

     StreamReader reader = new StreamReader(responseStream);

     List<string> result = new List<string>();

      while (!reader.EndOfStream)

      {

            result.Add(reader.ReadLine());

      }

      reader.Close();

      response.Close();

      //Last, sent the recevied directory Listcl

      return result;

}

For listing I created a DirectoryListing( ) method with a generic List<string> return type.

In the first line, it will ask for a web request that set up a connection between the client and the server.

The second line specifies the kind of job that the client wants to execute on the Server. So, we have defined ListDirectory, since we want the details of the directories and files.

Then, we assigned a network Credentials (in other words Authentication Process) by taking username and word as an argument.

And we defined a Web Response instance to accept a response from the server that uses the GetResponse() method.

To do this, we need a Stream between the Server and the Client.

For that, we have defined a Stream object and further a StreamReader to read those responses.

And now we create a generic list of string type to list the directory.

Using a while loop, we added the values to the generic list. Finally we return that list to the calling method.

Step 2

Second, we want to download a file from the FTP host to the local computer and it can be done by the DownlodFile property in the WebRequestMethod class.

public bool  Download(string file,string destination)

{

        try

        {

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(file);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            request.Credentials = new NetworkCredential(_userName, _word);

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(responseStream);

            StreamWriter writer = new StreamWriter(destination);

            writer.Write(reader.ReadToEnd());

            writer.Close();

            reader.Close();

            response.Close();

            return true;

        }

        catch

        {

            return false;

        }            

}

In the Download() method of the FtpClient class, we two arguments.

The first is a file, in other words the path of the file on the FTP server and the second is the destination that points to the destination path of the local computer.

The rest of the code is the same as earlier except the WebRequestMethod type.

Step 3

We will now try to upload from our local computers.So we define another method in the FtpClient class.

public void Upload(string source)
{

      string fileName = Path.GetFileName(source);

      Console.WriteLine(">>"+fileName);

      try

      {

          FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost/" + fileName);

          request.Method = WebRequestMethods.Ftp.UploadFile;

          request.KeepAlive = true;

          request.Useive = true;

          request.Credentials = new NetworkCredential(_userName, _word);

          StreamReader sourceStream = new StreamReader(source);

          byte[] fileContent = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

          request.ContentLength = fileContent.Length;

          Stream requestStream = request.GetRequestStream();

          requestStream.Write(fileContent, 0, fileContent.Length);

          FtpWebResponse response = (FtpWebResponse)request.GetResponse();

          response.Close();

          requestStream.Close();

          sourceStream.Close();

      }

      catch(Exception e)

      {

          Console.WriteLine("# "+e.Message);

      }

}

We set the KeepAlive property to true so that it will not timeout the request session.

Error: In this we get an exception in the GetResponse() method because of some FTP conflict. You can avoid this by using Remote FTP host rather than Local host.

Output Screen:



And when we select Directory Listing then:



And, in the second:



In the third case:



Conclusion

We will implement this concept in our next article and create a Windows Forms demo for this. For this you can see our solution file. Stay Raw; Stay Geek. Keep Coding

Up Next
    Ebook Download
    View all
    Learn
    View all