Lar*_*ard 0 .net c# ftp console-application .net-4.5
我正在尝试将相对较大的文件上传到FTP服务器(250-300mb).我在控制台应用程序中执行此操作.
当文件是几MB时,我的程序工作正常,但是大的文件导致:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive.
Run Code Online (Sandbox Code Playgroud)
我试图设置超时,但我仍然得到错误.
知道如何修改我的代码,所以我没有得到错误?
我的上传代码:
using(var fs = File.OpenRead(zipFileName))
{
var ms = new MemoryStream();
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int) fs.Length);
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUrl + "/" + zipFileName);
ftp.Credentials = new NetworkCredential(ftpUid, ftpPassword);
ftp.Timeout = 30000;
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
byte[] buffer = new byte[ms.Length];
ms.Read(buffer, 0, buffer.Length);
ms.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
Run Code Online (Sandbox Code Playgroud)
我使用您的代码将1 GB文件上传到我的FTP服务器.我也得到了System.Net.WebException.要修复它,我将超时设置为-1(不要超时).之后,上传工作.
ftp.Timeout = -1; // No Timeout
Run Code Online (Sandbox Code Playgroud)
另一方面,我不确定为什么要将文件读入MemoryStream然后将其放入byte []缓冲区.它会更快并且使用更少的内存来将FileStream复制到FTP RequestStream.
using (var fs = File.OpenRead(zipFileName))
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUrl + "/" + zipFileName);
ftp.Credentials = new NetworkCredential(ftpUid, ftpPassword);
ftp.Timeout = -1;
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
Stream ftpstream = ftp.GetRequestStream();
fs.CopyTo(ftpstream); // Copy the FileStream to the FTP RequestStream
ftpstream.Close();
// You should also check the response
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Console.WriteLine("Code: {0}", response.StatusCode);
Console.WriteLine("Desc: {0}", response.StatusDescription);
}
Run Code Online (Sandbox Code Playgroud)