0

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

还有其他想法吗?提前感谢您的帮助。

4

3 回答 3

0

160 MB 的文件不应导致 OutOfMemoryException。即使您尝试单独加载大文件(而不是一次上传所有 8 个文件),也会发生这种情况吗?抱歉,我无法将其放在评论中。没有评论权。

于 2013-04-26T16:58:42.327 回答
0

我猜它是一个带有文件上传控件的网络应用程序

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

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

“xxx”以 KB 为单位

于 2013-04-26T13:28:07.013 回答
0

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

于 2013-04-27T01:47:25.680 回答