我正在尝试将文件加载到 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[] 是静态的。
还有其他想法吗?提前感谢您的帮助。