我正在编写代码来检查文件是否存在。如果文件存在,它应该抛出 WebException。代码如下;如果我在 .NET 3.5 中运行此代码,它会抛出 WebException,但如果使用 .NET 4.0,则不会抛出异常。我希望抛出异常,以便我可以验证文件是否存在。
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;
请您参考如下方法:
如果你想通过 FTP 检查文件是否存在,那么 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
