C# System.OutOfMemoryException:FTP上载
我正在尝试将文件加载到FTP服务器。这是我的密码:C# System.OutOfMemoryException:FTP上载,c#,ftp,streamreader,ftpwebrequest,C#,Ftp,Streamreader,Ftpwebrequest,我正在尝试将文件加载到FTP服务器。这是我的密码: // Create the request. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(appSettingsFTP.ftpUrl + @"/" + filename); request.Method = WebRequestMethods.Ftp.UploadFile;
// Create the request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(appSettingsFTP.ftpUrl + @"/" + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 6000000; //set to 100 minutes
// Add the login credentials.
request.Credentials = new NetworkCredential(appSettingsFTP.ftpLogin, appSettingsFTP.ftpPassword);
// Grab the file contents.
StreamReader sourceStream = new StreamReader(appSettingsFTP.uploadFileDirectory + filename);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
// Copy the file contents to the outgoing stream.
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
LoggerFTP.Log(filename.ToString() + " " + "Upload Complete, Status: " + response.StatusCode, false);
除了其中一个文件(共有8个),其他一切似乎都正常工作。不起作用的文件是最大的,大约160000 kB。我得到的错误是:
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.String.ToCharArray()
at System.Text.Encoding.GetBytes(String s)
at CPMainSpringAPIExportsSC.UploadFTP.FTPUploadMethod(String viewname, String filename)
我相当肯定代码中的这一行发生了错误:
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
有没有一种方法可以在一个循环中而不是一次读取所有的数据?我想那会解决我的问题,但我想不出怎么做
此外,我还尝试使用+=运算符执行某些操作,但后来意识到字节[]是静态的
还有其他想法吗?提前感谢您的帮助 我猜这是一个带有文件上传控制的web应用程序 那么我想这应该可以解决问题了,将此添加到web.config:
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
“xxx”的大小为KB160 MB的文件不应导致OutOfMemoryException。即使您尝试单独加载大文件(而不是一次上载全部8个文件),也会发生这种情况吗?很抱歉,我无法将此添加到评论中。没有评论权。我发布了一个类似的答案。基本上,您需要将文件分块读取并上传到服务器