I am sending a large file (3gb) through ftp in c# and I'm geting an error while reading the file in the Source Stream when I am doing this :
StreamReader sourceStream = new StreamReader(@"C:\xxx\xxxx\xxx");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
The error :
An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll
The entire code :
// 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();
You can't read 3GB file into memory buffer. You have to do streamed transfer. Use file stream to read into a predefined buffer and then write that to ftp stream. Continue until you reach end of the file 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.