2

我正在尝试读取 500 MB 的文本文件以通过 HttpWebRequest 发送它的内容。根据我的要求,我不能分块发送数据。代码如下:

using (StreamReader reader = new StreamReader(filename))
{
    postData = reader.ReadToEnd();
}

byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "text/plain";
request.ContentLength = byteArray.Length;

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);

dataStream = response.GetResponseStream();

using (StreamReader reader = new StreamReader(dataStream))
{
    responseFromServer = reader.ReadToEnd();
}

Console.WriteLine(responseFromServer);
dataStream.Close();
response.Close();

读取这么大的文件会给我带来内存不足的异常。有没有办法我可以做到这一点?

4

2 回答 2

1

所有文件都以块的形式传输——这就是以太网数据包;这是一个单一的数据块。我敢打赌,该要求实际上意味着“必须在单个 Web 服务调用中传输此文件”。

假设是这种情况,您会将数据从磁盘读取到 64KB 缓冲区,然后将缓冲区写入请求。

request.ContentType = "text/plain";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
int BUFFER_SIZE = 65536;
byte[] buffer = new byte[BUFFER_SIZE];
using (StreamReader reader = new StreamReader(filename)) {
    int count = 0;
    while (true) {
        int count = reader.Read(buffer, 0, BUFFER_SIZE);
        dataStream.Write(buffer, 0, count);
        if (count < BUFFER_SIZE) break;
    }
}
dataStream.Close();
于 2012-07-24T23:50:48.920 回答
1

听起来您可能会遇到这个记录在案的问题HttpWebRequest。根据知识库文章,尝试将HttpWebRequest.AllowWriteStreamBuffering属性设置为false.

于 2012-07-24T23:51:04.490 回答