我在c#中通过ftp发送一个大文件(3gb),并且在我执行此操作时读取源流中的文件时发生错误:
StreamReader sourceStream = new StreamReader(@"C:\xxx\xxxx\xxx");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
错误:
未处理的类型' System.OutOfMemoryException'发生在mscorlib.dll
整个代码:
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx.xxx.xxx.xxx/file.iso");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "mdp");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(@"C:\xxx\xxx\xxx\xxxxxxxxx.iso");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
答案 0 :(得分:0)
您无法将3GB文件读入内存缓冲区。你必须做流式传输。使用文件流读入预定义的缓冲区,然后将其写入ftp stream。继续,直到到达文件流的末尾。
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx.xxx.xxx.xxx/file.iso");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "mdp");
// Copy the contents of the file to the request stream.
using (Stream sourceStream = File.OpenRead(@"C:\xxx\xxx\xxx\xxxxxxxxx.iso"))
using(Stream reqStrm = request.GetRequestStream())
{
byte[] buffer = new byte[1024 * 1024]; //1 MB buffer
int count = 0;
do
{
count = sourceStream.Read(buffer, 0, buffer.Length);
if (count > 0)
{
reqStrm.Write(buffer, 0, count);
}
}
while (count > 0);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();