Sponsored Ad

Sunday, January 3, 2010

C#.NET : How to Check File Existance on FTP Site

NameSpace to be included


    using System.IO;
    using System.Net;

  

Web.Config entries


         <add key="ftp_file_location" value="ftp://l01.Csharptalk.com/abc.csv"></add>
        <add key="ftp_login_name" value="csharp"></add>
        <add key="ftp_password" value="csharp"></add>

  

This is method to check if file exist on FTP Server, To use this function you need an FTP User name and FTP Password. System.Configuration.ConfigurationManager.AppSettings["ftp_login_name"] is taking user name directly from web.config and System.Configuration.ConfigurationManager.AppSettings["ftp_password"] is taking password from web.config. intead of taking from web.config you can directly write user name and password.

FTP File location is total path of file on ftp site. as given in web.config file. Please let me know if you face any problem.

 

Code Snippet
  1. private bool FTP_File_Exist(string ftpfilepath)
  2.     {
  3.         FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfilepath);
  4.         ftp.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["ftp_login_name"], System.Configuration.ConfigurationManager.AppSettings["ftp_password"]);
  5.         ftp.Method = WebRequestMethods.Ftp.GetFileSize;
  6.  
  7.         try
  8.         {
  9.             FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
  10.  
  11.         }
  12.         catch (WebException ex)
  13.         {
  14.             FtpWebResponse response = (FtpWebResponse)ex.Response;
  15.             if (response.StatusCode ==
  16.                 FtpStatusCode.ActionNotTakenFileUnavailable)
  17.             {
  18.                 return false;
  19.             }
  20.         }
  21.  
  22.         return true;
  23.  
  24.     }

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers