系统.OutOfMemoryException: FTP上传

本文关键字:上传 FTP OutOfMemoryException 系统 | 更新日期: 2023-09-27 18:10:57

我正在尝试将文件加载到FTP服务器。下面是我的代码:

                // 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个)之外,一切似乎都很好。不起作用的文件是最大的,大约有160,000 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());

是否有一种方法可以在循环中读取蒸汽阅读器而不是一次读取所有内容?我想那会解决我的问题,但我想不出怎么做。

另外,我尝试使用+=操作符做一些事情,但后来意识到byte[]是静态的。

还有其他想法吗?提前感谢任何帮助。

系统.OutOfMemoryException: FTP上传

我猜这是一个带有file-uploadcontrol的web应用程序

然后我想应该解决这个问题,把这个添加到你的web.config:

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xxx" />
  </system.web>
</configuration>

"xxx"的单位是KB

160mb的文件不应该引起OutOfMemoryException。即使您尝试单独加载大文件(而不是一次上传所有8个文件),也会发生这种情况吗?抱歉我没能在评论里写出来。没有注释权限

我在这里贴了一个类似的答案。基本上,您需要读取文件块并将其上传到服务器。