我正在尝试通过以下代码上传4 GB的zip文件。
相同的代码适用于较小的文件,但它不适用于大文件。我认为在关闭FileStream时会生成异常。
我收到此错误:
消息:基础连接已关闭:接收时发生意外错误。 Stacktrace:位于系统System.IO.Stream.Close()的System.Net.CommandStream.Dispose(布局处理)的System.Net.FtpWebRequest.RequestCallback(Object obj)处的System.Net.FtpWebRequest.SyncRequestCallback(Object obj)处System.Net.FtpWebRequest.FinishRequestStage上System.Net.ConnectionPool.PutConnection(PooledStream pooledStream,Object owningObject,Int32 creationTimeout,Boolean canReuse)的System.Net.ConnectionPool.Destroy(PooledStream pooledStream)中的.IO.Stream.Dispose()处于System.Net.FtpWeb上的System.Net.FtpWebRequest.SallRequestCallback(Object obj)处的System.Net.FtpWebRequest.RequestCallback(Object obj)处的System.Net.Com.St.DemandCream((例外))处于System.Net.Com.St.DemandCream(在System.IO.Stream.Close上的System.Net.FtpDataStream.Dispose(布尔处理)处的System.Net.FtpDataStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)处的System.Net.FtpWebRequest.DataStreamClosed(CloseExState closeState)( )在BackupUtility的System.IO.Stream.Dispose()处。 Program.UploadFileToFTP(String source)
我的FTP代码是:
private static bool UploadFileToFTP(string source)
{
try
{
String sourcefilepath = source; // e.g. "d:/test.docx"
String ftpurl = "myftpurl";
String ftpusername = "ftpusername"; // e.g. username
String ftppassword = "ftppassword"; // e.g. password
string ftpfullpath = "mylocalftpFilePath";
Console.WriteLine("Before Request. ftpfullpath:" + ftpfullpath);
// Console.ReadLine();
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Timeout = 6000000;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[8192];
using (Stream ftpstream = ftp.GetRequestStream())
{
//Stream ftpstream = ftp.GetRequestStream();
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
ftpstream.Write(buffer, 0, read);
}
ftpstream.Flush();
}
fs.Read(buffer, 0, buffer.Length);
fs.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}