FTP Using C# .NET

Introduction

In this article we will talk about FTP and using operations with C# .NET. We have FTP Client to interact and doing operation on FTP system so that we can easily drop a file and easily pick a file from FTP through source code to avoid manual operations.  Before starting we must know about FTP and their usage.

About FTP

Wikipedia states: 

"FTP is built on a client-server model architecture and uses separate control and data connections between the client and the server. FTP users may authenticate themselves with a clear-text sign-in protocol, normally in the form of a username and password, but can connect anonymously if the server is configured to allow it."

 "For secure transmission that protects the username and password, and encrypts the content, FTP is often secured with SSL/TLS (FTPS). SSH File Transfer Protocol (SFTP) is sometimes also used instead, but is technologically different."

Conceptual View

Step 1: Connection Establishment

In this step we will establish a connection and see how to connect it to your application,

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");  
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;  

// This example assumes the FTP site uses anonymous logon.  
request.Credentials = new NetworkCredential("maruthi", "******");  
request.KeepAlive = false;  
request.UseBinary = true;  
request.UsePassive = true; 

Required Namespace is: 

using System.Net;

Step 2: Connection Behavior

In this step we can define several behavior to your connection, cache definitions:

request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);   

Step 3: Read the Contents

The following code will help you to read the contents from FTP through your code, 

try    
{    
    // FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");    
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");    
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;    
    request.Credentials = new NetworkCredential("maruthi", "******");    
    request.KeepAlive = false;    
    request.UseBinary = true;    
    request.UsePassive = true;    
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();    
    Stream responseStream = response.GetResponseStream();    
    StreamReader reader = new StreamReader(responseStream);    
    Console.WriteLine(reader.ReadToEnd());    
    Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
    reader.Close();    
    response.Close();
}    
catch (Exception ex)    
{    
    Console.WriteLine(ex.Message.ToString());    
}  

It will show all the contents and directories of your FTP Drive,

 

The following snippet shows you to get particular content and I am trying to open the following content only,

 

try  
{  
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/6.txt");  
    request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);

    request.Method = WebRequestMethods.Ftp.DownloadFile;  

    request.Credentials = new NetworkCredential("maruthi", "******");  

    request.KeepAlive = false;  
    request.UseBinary = true;  
    request.UsePassive = true;  

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

    Stream responseStream = response.GetResponseStream();  

    StreamReader reader = new StreamReader(responseStream);  

    Console.WriteLine(reader.ReadToEnd());  

    Console.WriteLine("Download Complete", response.StatusDescription);  

    reader.Close();  

    response.Close();  
}  
catch (WebException e)  
{  
    Console.WriteLine(e.Message.ToString());  
    String status = ((FtpWebResponse)e.Response).StatusDescription;  
    Console.WriteLine(status);  
}  
catch(Exception ex)  
{  
    Console.WriteLine(ex.Message.ToString());  
}  

Response

 

I placed some program data in that file. So content seems like it. 

Step 4: Post a file

The following code will help you to post and send a file to FTP location. 

public static void PostDatatoFTP(int i)  
{  
    try  
    {  
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com"+@"\"+"TestFile0.txt");  
        request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);  
        request.Method = WebRequestMethods.Ftp.UploadFile;  
        request.Credentials = new NetworkCredential("maruthi", "******");  
        // Copy the contents of the file to the request stream.  
        StreamReader sourceStream = new StreamReader(@"E:\yourlocation\SampleFile.txt");  
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());  
        sourceStream.Close();  
        request.ContentLength = fileContents.Length;  
        Stream requestStream = request.GetRequestStream();  
        requestStream.Write(fileContents, 0, fileContents.Length);  
        requestStream.Close();  
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);  

        response.Close();  
    }  
    catch (WebException e)  
    {  
        Console.WriteLine(e.Message.ToString());  
        String status = ((FtpWebResponse)e.Response).StatusDescription;  
        Console.WriteLine(status);  
    }  
    catch(Exception ex)  
    {  
        Console.WriteLine(ex.Message.ToString());  
    }  
}  

Let us test and see whether the file is placed or not.

 

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/TestFile.txt");   

To read all file content.

Execute your console

static void Main(string[] args)  
{  
    Program.GetallContents();  
    Program.PostDatatoFTP(0);  
    Program.GetDataFromFTP();  
} 

References

Read more articles on C# Programming:


Similar Articles