2012-09-20 302 views
1

我試圖ulploade文件和FTP服務器,但是當我運行該方法它uploades只有2個文件,然後攤位。這檔在這一行上傳文件到FTP服務器

Stream uploadStream = reqFTP.GetRequestStream(); 

當我到達此行第一2次,程序會檢查我的證書,然後繼續,但攤位,從不第三時間的推移檢查我的證件。

這裏是全碼:

public void UploadLocalFiles(string folderName) 
     { 
      try 
      { 

       string localPath = @"\\localFolder\" + folderName; 
       string[] files = Directory.GetFiles(localPath); 
       string path;    

       foreach (string filepath in files) 
       { 
        string fileName = Path.GetFileName(filepath); 
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://serverIP/inbox/"+fileName)); 
        reqFTP.UsePassive = true; 
        reqFTP.UseBinary = true; 
        reqFTP.Credentials = new NetworkCredential("username", "password"); 
        reqFTP.EnableSsl = true; 
        ServicePointManager.ServerCertificateValidationCallback = Certificate; 
        reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 

        FileInfo fileInfo = new FileInfo(localPath [email protected]"\"+ fileName); 
        FileStream fileStream = fileInfo.OpenRead(); 

        int bufferLength = 2048; 
        byte[] buffer = new byte[bufferLength]; 

        Stream uploadStream = reqFTP.GetRequestStream(); 
        int contentLength = fileStream.Read(buffer, 0, bufferLength); 

        while (contentLength != 0) 
        { 
         uploadStream.Write(buffer, 0, bufferLength); 
         contentLength = fileStream.Read(buffer, 0, bufferLength); 
        } 
       } 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Error in GetLocalFileList method!!!!!" + e.Message); 
      } 

     } 

正如我Saied如何,當我到了它會檢查我的certificats,這裏的uloadStream代碼是我的證件方法

public bool Certificate(Object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) 
     { 
      { return cert.Issuer == "myCertificate"; } 
     } 

是有一些方法來只連接到FTP服務器一次,並執行證書一次,並舉行會議?因爲每次我想上傳或下載文件,因爲我想連接並驗證每個文件的證書..

+0

這可能不是你的問題的原因,但你應該使用後一直關閉流(在finally塊也許?):uploadStream.Close( ); – slawekwin

回答

1

您可能正在爲ServicePoint.ConnectionLimit Property,即2達到默認連接限制。 FtpWebRequest有一個ServicePoint屬性,您可以調整。上傳完成後,您需要關閉您的uploadStream

+0

當我之前添加這條catch線,這些文件不會上傳,當我刪除它們時只有2個文件上傳。 uploadStream.Close(); fileStream.Close(); – Lahib

+0

Im設置ServicePoint.ConnectionLimit = files.Length,它工作。但我不知道這是否是最佳做法。 – Lahib

2

只需添加這條線在你的應用程序的入口點:

System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); 
+0

這套證書可以被接受嗎? – Lahib

+0

是的。在使用Web服務時,我有類似的情況。所以,基本上如果有需要接受證書,這將做... –