2012-02-24 78 views
2

我正在編寫代碼來檢查文件是否存在。如果文件存在,它應該拋出WebException。代碼如下;如果我在.NET 3.5中運行此代碼,則會引發WebException,但如果使用.NET 4.0,則不會拋出異常。我想要異常被拋出,所以我可以驗證文件的存在。代碼拋出WebException在.NET 3.5中工作,但不在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 = "[email protected]"; 
    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; 
+0

不是很確定,但嘗試[改變'UsePassive'財產(http://stackoverflow.com/questions/4604693/ftp-throws-webexception-only-in-net-4-0)對於ftprequest – V4Vendetta 2012-02-24 06:37:33

+0

是否仍然拋出異常?抓住更一般的例外,看看它是什麼。 – rikitikitik 2012-02-24 08:23:10

回答

0

如果你想通過FTP檢查文件的存在,然後check out this answer

我建議使用下面的WebRequestMethod代替,這對我測試的所有服務器都適用,即使是那些不會返回文件大小的服務器。

WebRequestMethods.Ftp.GetDateTimestamp 
+0

另外一個想法是使用'request.Method = WebRequestMethods.Ftp.ListDirectoryDe​​tails;'和解析列表來找到flie。由於並非所有FTP Web請求類型均由Microsoft正確實施。 – Marcin 2012-02-24 08:56:47

+0

感謝您回覆其工作檔案............ – LetMeIN 2012-02-24 10:20:46

相關問題