• How to FTP a file through C#

    by Venkata Koppaka | Feb 05, 2010

    .NET Framework gives us a nice little API to FTP a file to a server using C#, VB.NET . This article is an attempt to put it to code.

    Please note that I am only doing a File Upload using FTP. File Download will follow soon.

     Add a reference to Sytem.Net to the application - and use the following fragment. -

    1 string ftpFileName = @"C:\temp\Foo.txt;
    2
    3             //Get the fileInfo to be uploaded
    4             FileInfo fileInfo = new FileInfo(ftpFileName);
    5
    6                 //Create a FTPWebRequest
    7                 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + Settings.Default.FTPServer + @"/" + fileInfo.Name); 
    8                 request.Method = WebRequestMethods.Ftp.UploadFile; 
    9  
    10                 //Setting Credentials 
    11                 request.Credentials = new NetworkCredential(Settings.Default.FTPUserName, Settings.Default.FTPPassword); 
    12  
    13                 //Setup a stream for the request and a stream for the file that we are uploading 
    14                 Stream ftpStream = request.GetRequestStream(); 
    15                 FileStream file = File.OpenRead(ftpFileName); 
    16  
    17  
    18                 //Variables to read the file 
    19                 int length = 1024; 
    20                 byte[] buffer = new byte[length]; 
    21                 int bytesRead = 0; 
    22  
    23                 //Write the file to requerst stream 
    24                 do 
    25                 { 
    26                     bytesRead = file.Read(buffer, 0, length); 
    27                     ftpStream.Write(buffer, 0, bytesRead); 
    28                 } while (bytesRead != 0); 
    29  
    30                 //Flush / Close 
    31                 file.Close(); 
    32                 ftpStream.Close(); 

    Please note that I am using a Settings file to read the FTPServer, FTPUsername and FTPPassword. You could use a hardcoded / read from DB / XML value there.

    Hope this helps,

    Cheers,

    Venkata


    Go comment!