2012-09-20 243 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服务时,我有类似的情况。所以,基本上如果有需要接受证书,这将做... –