我在使用流将多个文件逐个上传到ftp时遇到问题。 当我尝试关闭流(ftpstream.close())写入流后,上传的文件被删除。 如果我不使用.close(),很少上传文件,但第三次调用getstreamrequest()(每个文件上传调用)会给出“此操作超时错误”
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);
答案 0 :(得分:1)
我认为您的代码中出现的问题是您拨打ftpStream = request.GetRequestStream();
的地方以及使用ftpStream.Close();
关闭流的位置
很多}
介于两者之间,这意味着您将获得多个请求流而无需正确关闭它们。
您可能需要在与请求它相同的代码级别关闭流。