在 .Net 中下载失败

Download is failing in .Net

您好,我在这段代码中遇到了问题:

// 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 时,它会失败。我已经尝试过网络客户端的 downloadfileAsyc,但它也失败了。有没有其他方法可以处理这个问题的大文件?

分配的缓冲区大小大于预期的文件大小。

byte[] byteBuffer = new byte[65536];

因此,如果文件大小为 1GiB,您将分配一个 1GiB 的缓冲区,然后尝试在一次调用中填充整个缓冲区。 此填充可能会减少 return 个字节,但您仍然分配了整个缓冲区。请注意,.NET 中单个数组的最大长度是 32 位数字,这意味着即使您将程序重新编译为 64 位并且实际上有足够的可用内存。

供您参考,请访问此 link: