2014-02-26 34 views
0

我有設置代碼來執行FTP PUT並將文件傳輸到FTP服務器。首先我有一個方法來檢查文件是否存在於目標位置。如果有,我有另一種方法刪除文件。然後我執行FTP PUT到目標位置。如何在一個FTP連接中執行多種方法

目前,我通過設置3個獨立的FTP連接到同一臺服務器來執行這3種方法。但是,我想通過一個連接到服務器來執行所有3種方法。原因是因爲在打開到同一FTP服務器的多個連接後出現以下錯誤:「現有連接被遠程主機強行關閉。」

以下是以下3種功能。第一種方法GetFileFromRemoteServer用於查看目標路徑上的FTP服務器上是否存在文件。我在某些情況下使用正則表達式來獲得部分名稱匹配,或者在其他情況下只是進行全名匹配。

我在線研究,有人說可以使用相同的ftp請求對象,只是執行所需的所有方法,然後關閉連接。我試圖看看它是否可以在同一個請求對象上執行多個方法,並且出現此錯誤:請求提交後無法執行此操作。

有沒有辦法使用一個連接到服務器執行所有這些?

謝謝你,我真的很感謝你的幫助!

public static List<FTPLineResult> GetFileFromRemoteServer(bool isSsl, string username, string password, string fileName, string dir, Regex regexPattern, 
     bool getSingleFile = false) 
{ 
     var output = new List<FTPLineResult>(); 
     var parser = new FTPLineParser(); 
     var isDone = false; 

     var request = (FtpWebRequest)WebRequest.Create(dir); 
     request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; 
     request.ConnectionGroupName = ConfigurationManager.AppSettings["ftpConnectionGroup"]; 
     request.KeepAlive = true; 

     request.Credentials = new NetworkCredential(username, password); 
     request.UsePassive = true; 

     if (isSsl) 
     { 
      request.EnableSsl = true; 
     } 
     else 
     { 
      request.EnableSsl = false; 
     } 

     using (var response = (FtpWebResponse)request.GetResponse()) 
     { 
      using (var responseStream = response.GetResponseStream()) 
      { 
       using (var reader = new StreamReader(responseStream, Encoding.ASCII)) 
       { 
        while (!isDone && !reader.EndOfStream) 
        { 
         var result = parser.Parse(reader.ReadLine()); 

         //if "*" is in file name, which means get partial match, replacing * with real file name content 
         if (regexPattern != null) 
         { 
          if (regexPattern.IsMatch(result.Name.ToLower().Trim())) 
          { 
           output.Add(result); 
          } 

         } 

         else if (result.Name.ToLower().Trim() == fileName.ToLower().Trim()) 
         { 
          output.Add(result); 

          isDone = true; 
         } 
        } 

        return output; 
       } 
      } 
     } 
    } 


private void DeleteExistingTargetFile() 
{ 
     // Get the object used to communicate with the server. 
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_params.FinalFolderTarget); 
     request.Method = WebRequestMethods.Ftp.DeleteFile; 
     request.Credentials = new NetworkCredential(_params.Username, _params.Password); 
     request.UsePassive = true; 

     request.ConnectionGroupName = ConfigurationManager.AppSettings["ftpConnectionGroup"]; 
     request.KeepAlive = true; 

     if (_params.IsSsl) 
     { 
      request.EnableSsl = true; 
     } 
     else 
     { 
      request.EnableSsl = false; 
     } 

     using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 
     { 
      var status = response.StatusDescription; 
     } 
    } 

private void DoFtpPut(Dictionary<StatusEnum, string> statusDict) 
{ 
     int buffLength = 2048; 
     byte[] buff = new byte[buffLength]; 
     System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_params.SourceFilename); 

     var request = (FtpWebRequest)WebRequest.Create(new Uri(_params.TargetFilename)); 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.ConnectionGroupName = ConfigurationManager.AppSettings["ftpConnectionGroup"]; 
     request.KeepAlive = true; 

     request.Credentials = new NetworkCredential(_params.Username, _params.Password); 
     request.UsePassive = true; 

     if (_params.IsSsl) 
     { 
      request.EnableSsl = true; 
     } 
     else 
     { 
      request.EnableSsl = false; 
     } 

     using (var _Stream = request.GetRequestStream()) 
     { 
      //read file one chunk at a time in order to avoid out of memory exception 
      using (var fileStream = _FileInfo.OpenRead()) 
      { 
       var contentLen = fileStream.Read(buff, 0, buffLength); 

       while (contentLen != 0) 
       { 
        _Stream.Write(buff, 0, contentLen); 
        contentLen = fileStream.Read(buff, 0, buffLength); 
       } 
      } 
     } 

     statusDict[StatusEnum.ftpStatus] = Constants.SUCCESS_STATUS; 
    } 
+3

我不認爲你可以用'FtpWebRequest'類做到這一點。嘗試一個正確的FTP客戶端 - 例如,http://netftp.codeplex.com/ –

+0

我認爲你是對的。我現在正在嘗試這個ftp客戶端:http://ftplib.codeplex.com/感謝您的幫助! – jre247

回答

0

我找不出一種方法來做FTPPUT只有一個連接使用FtpWebRequest類。然而,使用FtpLib庫允許我完成我想要的操作,即檢查文件是否存在於ftp服務器目標位置,如果它確實刪除,然後執行ftp放置,最後使用重命名將文件移動到最終位置。

這裏就是我下載FTPLIB庫:ftplib.codeplex.com

這裏的代碼如下:

using (FtpConnection ftp = new FtpConnection(host, _params.Username, _params.Password)) 
{ 

      try 
      { 
       ftp.Open(); /* Open the FTP connection */ 
       ftp.Login(); /* Login using previously provided credentials */ 

       ftp.PutFile(_params.SourceFilename, _params.TargetFilename); /* upload /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ 

       if (!ftp.DirectoryExists(_params.FinalDir)) /* check that a directory exists */ 
       { 
        ftp.CreateDirectory(_params.FinalDir); 
       } 

       if (ftp.FileExists(_params.FinalLocation)) 
       { 
        ftp.RemoveFile(_params.FinalLocation); 
       } 

       ftp.RenameFile(target, _params.FinalLocation); 

       statusDict[StatusEnum.ftpStatus] = Constants.SUCCESS_STATUS; 

      } 
      catch (Exception ex) 
      { 
       statusDict[StatusEnum.ftpStatus] = Constants.ERROR_STATUS; 
      } 
     } 
相關問題