我在使用流将多个文件逐一上传到ftp时遇到问题。当我在写入流后尝试关闭流(ftpstream.close())时,上传的文件会被删除。如果我不使用.close(),上传的文件很少,但对getstreamrequest()的第三次调用(每次上传文件都会调用)会给出"This operation is timeout error"
using (Stream stream = new MemoryStream(File.ReadAllBytes(fullPath)))
{
stream.Position = 0;
stream.Seek(0, SeekOrigin.Begin);
string uri = String.Format("{0}/{1}", _FTPURL, fileName);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
request.Credentials = new NetworkCredential(_FTPUSRNAME, _FTPPSWD);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.ContentLength = stream.Length;
request.EnableSsl = false;
int bufferLength = 2048*20;
byte[] buffer = new byte[bufferLength];
int contentLength;
ftpStream = request.GetRequestStream();
contentLength = stream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
ftpStream.Write(buffer, 0, contentLength);
contentLength = stream.Read(buffer, 0, bufferLength);
}
}
pageNo++;
}
}
ftpStream.Close();
}
while (!hasPaginationCompleted);
我认为代码中的错误在于调用ftpStream = request.GetRequestStream();
和使用ftpStream.Close();
关闭流的地方
大量的}
介于两者之间,这意味着您将在没有正确关闭它们的情况下获得多个请求流。
您可能需要在与请求相同的代码级别中关闭流。