從ftp服務器上下載文件之前,我想檢查一下是否存在,如果不存在,如果不存在,那麼會拋出異常。該代碼示例在文件不存在時起作用。但是,當文件存在時,在執行該行之後; 「ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;」它會跳轉第二個catch塊並打印「錯誤:請求提交後無法執行此操作。」有什麼意思,我不能看到..謝謝你的答案。在下載之前檢查文件是否存在於ftp服務器上
public void fileDownload(string fileName)
{
stream = new FileStream(filePath + fileName, FileMode.Create);
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
ftpRequest.Credentials = new NetworkCredential(userName, password);
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
response = (FtpWebResponse)ftpRequest.GetResponse();
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.UseBinary = true;
response = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = response.GetResponseStream();
cl = response.ContentLength;
bufferSize = 2048;
buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
stream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
stream.Close();
response.Close();
Console.WriteLine("File : " + fileName + " is downloaded from ftp server");
}
catch (WebException ex)
{
FtpWebResponse res = (FtpWebResponse)ex.Response;
if (res.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
stream.Close();
File.Delete(filePath + fileName);
Console.WriteLine("File : " + fileName + " does not exists on ftp server");
System.Diagnostics.Debug.WriteLine("Error: " + fileName + " is not available on fpt server");
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
}
}
是的,你是對的。我通過編寫fileExist()方法處理它,以避免重複相同的行。它的工作感謝您的回答 – anarhikos 2010-07-26 13:48:17
我得到了同樣的錯誤:「此操作不能在提交請求後執行。」我試圖下載一個文件並上傳另一個重用相同請求對象的文件。把它們分解成單獨的請求對象就能實現。謝謝。 – MikeTeeVee 2012-01-23 07:44:17