我试图将文件ulploade和ftp Server,但是当我运行该方法时,它只上传2个文件,然后停止。它停在这条线上
Stream uploadStream = reqFTP.GetRequestStream();
当我前两次到达此行时,程序会检查我的证书然后继续,但第三次停止并且永远不会继续检查我的证书。
这是完整的代码:
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服务器一次,并执行一次证书并保持会话?每当我想要上传或下载文件时,我都会正确连接并验证每个文件的证书..
答案 0 :(得分:2)
只需在应用的入口点添加此行:
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
答案 1 :(得分:1)
您可能正在达到ServicePoint.ConnectionLimit Property的默认连接限制,即2
。 FtpWebRequest
具有ServicePoint
属性,您可以调整。上传完成后,您需要立即关闭uploadStream
。