2

I am writing code to check whether a file exists or not. If the file exists it should throw a WebException. The code is below; if I run this code in .NET 3.5 it throws a WebException, but if use .NET 4.0 the exception is not thrown. I want the exception to be thrown so I can validate the file's existence.

bool IsExists = true;
try
{
    // string ftpServer = "FTP://111.111.111.111/16FebTo15Mar/Backup/MT_Backup/";
    string userName = "gff";
    // string filename = "sachin";
    string password = "gff@123";
    string ftppath= "FTP://111.111.111.111/16FebTo15Mar/Backup/MT_Backup/bh/"; 
                    // Ftpurl + new FileInfo(EmpFldr).Name + "/";

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftppath);
    request.Credentials = new NetworkCredential(userName, password);
    request.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
    // request.Method = WebRequestMethods.Ftp.MakeDirectory;
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    IsExists = false;
}
return IsExists;
praseodym
  • 2,134
  • 15
  • 29
Sachin
  • 75
  • 1
  • 3
  • 12
  • Not very sure but try [changing the `UsePassive` property](http://stackoverflow.com/questions/4604693/ftp-throws-webexception-only-in-net-4-0) for the ftprequest – V4Vendetta Feb 24 '12 at 06:37
  • Is an exception still being thrown? Catch the more general exception and see what it is. – rikitikitik Feb 24 '12 at 08:23

1 Answers1

0

If you want to check for the existence of a file via FTP then check out this answer.

I'd recommend using the following WebRequestMethod instead, this works for me on all servers I tested, even ones which would not return a file size.

WebRequestMethods.Ftp.GetDateTimestamp
Community
  • 1
  • 1
ta.speot.is
  • 26,914
  • 8
  • 68
  • 96
  • Also other idea is use `request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;` and parse list to find flie. Since not all FTP web request types are properly implemneted by Microsoft. – Marcin Feb 24 '12 at 08:56