C# 在.Net中下载失败
您好,我在此代码中遇到问题:C# 在.Net中下载失败,c#,asp.net,.net,download,webrequest,C#,Asp.net,.net,Download,Webrequest,您好,我在此代码中遇到问题: // Function will return the number of bytes processed // to the caller. Initialize to 0 here. int bytesProcessed = 0; // Assign values to these objects here so that they can // be referenced in the finally block Stream remoteStream =
// Function will return the number of bytes processed
// to the caller. Initialize to 0 here.
int bytesProcessed = 0;
// Assign values to these objects here so that they can
// be referenced in the finally block
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;
// Use a try/catch/finally block as both the WebRequest and Stream
// classes throw exceptions upon error
try
{
// Create a request for the specified remote file name
WebRequest request = WebRequest.Create(remoteFilename);
request.Method = "GET";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(uName + ":" + pwd));
request.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
if (request != null)
{
// Send the request to the server and retrieve the
// WebResponse object
response = request.GetResponse();
if (response != null)
{
// Once the WebResponse object has been retrieved,
// get the stream object associated with the response's data
remoteStream = response.GetResponseStream();
// Create the local file
localStream = File.Create(localFilename);
// Allocate a 1k buffer
byte[] buffer = new byte[1024];
int bytesRead;
long totalBytesToProcess = response.ContentLength;
// Simple do/while loop to read from stream until
// no bytes are returned
do
{
// Read data (up to 1k) from the stream
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
// Write the data to the local file
localStream.Write(buffer, 0, bytesRead);
// Increment total bytes processed
bytesProcessed += bytesRead;
log(resourcesPath + "/BytesRecieved.txt", bytesProcessed.ToString()+"/"+ totalBytesToProcess.ToString(), false);
} while (bytesRead > 0);
}
}
}
catch (Exception ex)
{
Response.Write(ex);
// log(resourcesPath +"/Logs.txt",);
}
finally
{
// Close the response and streams objects here
// to make sure they're closed even if an exception
// is thrown at some point
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (localStream != null) localStream.Close();
}
// Return total bytes processed to caller.
return bytesProcessed;
它能够下载200 mb大小的小文件,不幸的是,当文件大小飙升到1gb以上时,它就失败了。我试过下载web客户端的FileAsyc,但也失败了。是否有其他方法处理此问题的大文件?分配大于预期文件大小的缓冲区大小 字节[]byteBuffer=新字节[65536] 因此,如果文件大小为1GB,则分配1GiB缓冲区,然后尝试在一次调用中填充整个缓冲区。 此填充可能返回更少的字节,但您仍然分配了整个缓冲区。请注意,.NET中单个数组的最大长度是32位数字,这意味着即使您将程序重新编译为64位,并且实际上有足够的可用内存 请访问此链接以供参考:
失败意味着什么?有错误消息吗?请注意,您可以通过使用
using
语句而不是显式调用Close
来删除一堆代码,也可以通过调用Stream.CopyTo
来删除代码,除非日志记录特别重要。实际上不是错误消息。它只是停止下载,文件就被破坏了。这是垃圾,就这么停了?代码完成了吗?@john是的,代码实际上已经完成了。它能够下载小文件。这似乎解决了我的问题。我将继续对我将要进行的过程保持警惕,比如下载更大的文件。非常感谢。@OneLazy很高兴听到它解决了您的问题。:)