System.OutOfMemoryException:FTP上传

时间:2013-04-26 13:24:13

标签: c# ftp streamreader ftpwebrequest

我正在尝试将文件加载到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 []是静态的。

还有其他想法吗?在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

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

然后我想应该解决问题,将其添加到您的web.config:

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

&#34; XXX&#34;是KB

答案 1 :(得分:0)

160 MB的文件不应该导致OutOfMemoryException。即使您尝试单独加载大文件(而不是一次上传所有8个文件),是否会发生这种情况?对不起,我不能把它放在评论中。没有评论权。

答案 2 :(得分:0)

我发布了一个类似的答案here。基本上你需要以块的形式读取文件并将其上传到服务器。