在下载之前检查文件是否存在于ftp服务器上

问题描述:

从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); 
      } 
     } 

我的理解是,你必须创建一个新的FtpWebRequest的每一个请求你做。因此,在再次设置Method之前,您必须创建一个新的并再次设置凭据。因此,相当多的是,你不得不重复以下两行:

ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName)); 
ftpRequest.Credentials = new NetworkCredential(userName, password); 
+0

是的,你是对的。我通过编写fileExist()方法处理它,以避免重复相同的行。它的工作感谢您的回答 – anarhikos 2010-07-26 13:48:17

+0

我得到了同样的错误:“此操作不能在提交请求后执行。”我试图下载一个文件并上传另一个重用相同请求对象的文件。把它们分解成单独的请求对象就能实现。谢谢。 – MikeTeeVee 2012-01-23 07:44:17

当您连接到FTP服务器,你可以指定的URI作为“FTP // ftp.domain.com/somedirectory”,但这种转换到:“ftp://ftp.domain.com/homedirectoryforftp/somedirectory”。为了能够定义完整的根目录,使用“ftp://ftp.domain.com//somedirectory”,它转换为计算机上的somedirectory。