0

感谢您对我在旨在为 Web 服务流式传输文件的代码中看到的 OOM(内存不足)问题提出了很好的建议。[我希望可以启动另一个提供更多细节的线程。]根据建议,我缩小了用于从文件读取的缓冲区大小,看起来内存消耗更好,但我仍然看到OOM 问题,我发现文件大小只有 5MB。我可能想处理十倍大的文件。

我的问题现在似乎与使用 TextWriter 有关。

我按如下方式创建了一个请求[进行了一些编辑以缩小代码]:

HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(new Uri(strURL));
oRequest.Method = httpMethod;
oRequest.ContentType = "application/atom+xml";
oRequest.Headers["Authorization"] = getAuthHeader();
oRequest.ContentLength = strHead.Length + strTail.Length + longContentSize;
oRequest.SendChunked = true;

using (TextWriter tw = new StreamWriter(oRequest.GetRequestStream()))
{
    tw.Write(strHead);
    using (FileStream fileStream = new FileStream(strPath, FileMode.Open, 
           FileAccess.Read, System.IO.FileShare.ReadWrite))
    {
        StreamEncode(fileStream, tw);
    }
    tw.Write(strTail);
}
.....

调用例程:

public void StreamEncode(FileStream inputStream, TextWriter tw)
{
    // For Base64 there are 4 bytes output for every 3 bytes of input
    byte[] base64Block = new byte[9000];
    int bytesRead = 0;
    string base64String = null;

    do
    {
        // read one block from the input stream
        bytesRead = inputStream.Read(base64Block, 0, base64Block.Length);

        // encode the base64 string
        base64String = Convert.ToBase64String(base64Block, 0, bytesRead);

        // write the string
        tw.Write(base64String);


    } while (bytesRead !=0 );

}

由于潜在的大内容,我应该使用 TextWriter 以外的东西吗?能够创建请求的整个有效负载似乎非常方便。

这完全是错误的方法吗?我希望能够支持非常大的文件。

4

0 回答 0