【问题标题】:Uploading files to FTP Server上传文件到 FTP 服务器
【发布时间】:2012-09-20 06:22:40
【问题描述】:

我正在尝试 ulploade 文件到 ftp 服务器,但是当我运行该方法时,它只上传 2 个文件然后停止。它停在这条线上

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 +@"\"+ 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);
            }

        }

正如我所说,当我到达 uloadStream 代码时,它会检查我的证书,这是我的证书方法

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

有没有办法只连接一次ftp服务器,做一次证书并保持会话?因为每次我想上传或下载文件时,我都会连接并验证每个文件的证书..

【问题讨论】:

  • 这可能不是您的问题的原因,但您应该在使用后始终关闭流(可能在 finally 块中?):uploadStream.Close();

标签: c# c#-4.0 ftp c#-3.0 sftp


【解决方案1】:

只需在应用的入口点添加这一行:

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

【讨论】:

  • 是的。我在使用 Web 服务时遇到了类似的情况。所以,基本上,如果需要接受证书,这会做......
【解决方案2】:

您可能正在达到ServicePoint.ConnectionLimit Property 的默认连接限制,即2FtpWebRequest 有一个可以调整的 ServicePoint 属性。上传完成后,您需要关闭 uploadStream

【讨论】:

  • 在我的捕获行之前添加此文件时,文件不会上传,当我删除它们时,只会上传 2 个文件。上传流。关闭(); fileStream.Close();
  • 我正在设置 ServicePoint.ConnectionLimit = files.Length,它可以工作。但我不知道这是否是最佳做法。