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,
  1. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");  
  2.                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;  
  3.   
  4.                // This example assumes the FTP site uses anonymous logon.  
  5.                request.Credentials = new NetworkCredential("maruthi""******");  
  6.                request.KeepAlive = false;  
  7.                request.UseBinary = true;  
  8.                request.UsePassive = true;  
Required Namespace is: 
  1. using System.Net;  
Step 2: Connection Behavior
 
In this step we can define several behavior to your connection, cache definitions:
  1. 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, 
  1. try    
  2.            {    
  3.                // FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");    
  4.                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/");    
  5.                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;    
  6.     
  7.                
  8.                request.Credentials = new NetworkCredential("maruthi""******");    
  9.                request.KeepAlive = false;    
  10.                request.UseBinary = true;    
  11.                request.UsePassive = true;    
  12.     
  13.     
  14.                FtpWebResponse response = (FtpWebResponse)request.GetResponse();    
  15.     
  16.                Stream responseStream = response.GetResponseStream();    
  17.                StreamReader reader = new StreamReader(responseStream);    
  18.                Console.WriteLine(reader.ReadToEnd());    
  19.     
  20.                Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);    
  21.     
  22.                reader.Close();    
  23.                response.Close();
  24.                   
  25.            }    
  26.            catch (Exception ex)    
  27.            {    
  28.                Console.WriteLine(ex.Message.ToString());    
  29.            }    
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,
 
 
  1. try  
  2.            {  
  3.                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/6.txt");  
  4.   
  5.                request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);  
  6.   
  7.                request.Method = WebRequestMethods.Ftp.DownloadFile;  
  8.   
  9.                request.Credentials = new NetworkCredential("maruthi""******");  
  10.   
  11.                request.KeepAlive = false;  
  12.                request.UseBinary = true;  
  13.                request.UsePassive = true;  
  14.   
  15.                FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  16.   
  17.                Stream responseStream = response.GetResponseStream();  
  18.   
  19.                StreamReader reader = new StreamReader(responseStream);  
  20.   
  21.                Console.WriteLine(reader.ReadToEnd());  
  22.   
  23.                Console.WriteLine("Download Complete", response.StatusDescription);  
  24.   
  25.                reader.Close();  
  26.   
  27.                response.Close();  
  28.            }  
  29.            catch (WebException e)  
  30.            {  
  31.                Console.WriteLine(e.Message.ToString());  
  32.                String status = ((FtpWebResponse)e.Response).StatusDescription;  
  33.                Console.WriteLine(status);  
  34.            }  
  35.           catch(Exception ex)  
  36.            {  
  37.                Console.WriteLine(ex.Message.ToString());  
  38.            }  
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. 
  1. public static void PostDatatoFTP(int i)  
  2.        {  
  3.            try  
  4.            {  
  5.                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com"+@"\"+"TestFile0.txt");  
  6.                request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);  
  7.                request.Method = WebRequestMethods.Ftp.UploadFile;  
  8.                request.Credentials = new NetworkCredential("maruthi""******");  
  9.                // Copy the contents of the file to the request stream.  
  10.                StreamReader sourceStream = new StreamReader(@"E:\yourlocation\SampleFile.txt");  
  11.                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());  
  12.                sourceStream.Close();  
  13.                request.ContentLength = fileContents.Length;  
  14.                Stream requestStream = request.GetRequestStream();  
  15.                requestStream.Write(fileContents, 0, fileContents.Length);  
  16.                requestStream.Close();  
  17.                FtpWebResponse response = (FtpWebResponse)request.GetResponse();  
  18.                Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);  
  19.   
  20.                response.Close();  
  21.            }  
  22.            catch (WebException e)  
  23.            {  
  24.                Console.WriteLine(e.Message.ToString());  
  25.                String status = ((FtpWebResponse)e.Response).StatusDescription;  
  26.                Console.WriteLine(status);  
  27.            }  
  28.            catch(Exception ex)  
  29.            {  
  30.                Console.WriteLine(ex.Message.ToString());  
  31.            }  
  32.        }  
Let us test and see whether the file is placed or not.
 
  1. FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/TestFile.txt");   
To read all file content.
 
Execute your console
  1. static void Main(string[] args)  
  2.         {  
  3.             Program.GetallContents();  
  4.             Program.PostDatatoFTP(0);  
  5.             Program.GetDataFromFTP();  
  6.         }  

References:

Read more articles on C# Programming:

Up Next
    Ebook Download
    View all
    Learn
    View all