Ftp Upload提供异常无法将数据写入传输连接。远程主机强制关闭现有连接

时间:2012-01-06 15:11:10

标签: c# exception ftp ftpwebrequest ftpwebresponse

我有一个Windows窗体应用程序,其中我使用后台工作程序来ftp上传文件。成功上传209个文件后,文件错误的大小仅为7.8kb While Processing Img1.jpg Unable to write data to the transport connection. An existing connection was forcibly closed by the remote host

string uri1;

ftpInfoUpload = LoadHostedSiteData(hs);
ftpInfoUpload[5] = imgRow["Filename"].ToString();

uri1 = String.Format("ftp://{0}/{1}/images/{2}", ftpInfoUpload[1], ftpInfoUpload[2], ftpInfoUpload[5]);

requestUpload = (FtpWebRequest)WebRequest.Create(uri1);
requestUpload.UsePassive = false;
requestUpload.UseBinary = true;
requestUpload.Method = WebRequestMethods.Ftp.UploadFile;
requestUpload.Credentials = new NetworkCredential(ftpInfoUpload[3], ftpInfoUpload[4]);


requestUpload.ContentLength = memStream.Length;
byte[] buff = new byte[bufferSize];
int contentLen;

// Stream to which the file to be upload is written
Stream strm = requestUpload.GetRequestStream();
memStream.Seek(0, SeekOrigin.Begin);
contentLen = memStream.Read(buff, 0, bufferSize);
                            // Till Stream content ends
while (contentLen > 0)
{   
    // Write Content from the file stream to the FTP   Upload Stream
    strm.Write(buff, 0, contentLen);
    contentLen = memStream.Read(buff, 0, bufferSize);
}

//Close the file stream and the Request Stream
strm.Close();
strm.Dispose();
ftpStream.Close();
memStream.Close();
//responseUpload.Close();
responseDownload.Close();

想法发生了什么?

1 个答案:

答案 0 :(得分:1)

我已设置ftprequest.KeepAlive=true&设置ftprequest.ConnectionGroupName = "Some Value",以便底层代码不必具有具有相同ftp服务器的新创建连接。我找到了这个解决方案here。我还发现this很有帮助。每次传输可能导致异常的文件时,请确保不要创建新的NetworkCredential对象。我已经测试了我的代码两次传输300个文件,似乎工作得很好而且很快。设置KeepAlive=false会使转移变慢