C#有效读取流内容,读取数量限制

问题描述 投票:0回答:1

我有一个案例,Web API调用返回一个非常大的字符串响应。我打电话如下:

var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(blobStream.CopyToBytes()), 
                         "upload", Path.GetFileName(fileName));

var response = await _httpClient.PostAsync("api/v1/textResponse", multipartContent);
int responeLength = response.Content.Headers.ContentLength.HasValue ? 
                    (int)response.Content.Headers.ContentLength.Value : -1;

response.EnsureSuccessStatusCode();

我只需要处理来自响应的第一个1Mb数据,所以如果响应小于1Mb,我会读取所有数据,但如果它更多,我会很难停止读取1Mb。

我正在寻找最有效的方法来做这个阅读。我试过这段代码:

// section above...

response.EnsureSuccessStatusCode();

string contentText = null;

if (responeLength < maxAllowedLimit) // 1Mb
{
     // less then limit - read all as string.
     contentText = await response.Content.ReadAsStringAsync();
} 
else {
     var contentStream = await response.Content.ReadAsStreamAsync();
     using (var stream = new MemoryStream())
     {
         byte[] buffer = new byte[5120]; // read in chunks of 5KB
         int bytesRead;
         while((bytesRead = contentStream.Read(buffer, 0, buffer.Length)) > 0)
         {
             stream.Write(buffer, 0, bytesRead);
         }
         contentText = stream.ConvertToString();
     }
}

这是最有效的方式,我如何限制读取的数量(其他)。我试过这段代码,它总是返回一个空字符串。还有:

ReadAsStringAsync()
ReadAsByteArrayAsync()
ReadAsStreamAsync()
LoadIntoBufferAsync(int size)

这些方法中的任何一种都更有效吗?

提前感谢任何指针!

c# stream memorystream
1个回答
2
投票

我怀疑这样做最有效(但仍然正确)的方式可能是这样的。由于您对读取的字节数有限制,而不是字符数,因此更加复杂,因此我们无法使用StreamReader。请注意,我们必须注意不要在代码点中间停止读取 - 在许多情况下,使用多个字节表示单个字符,并且在中途停止将是一个错误。

const int bufferSize = 1024;
var bytes = new byte[bufferSize];
var chars = new char[Encoding.UTF8.GetMaxCharCount(bufferSize)];
var decoder = Encoding.UTF8.GetDecoder();
// We don't know how long the result will be in chars, but one byte per char is a
// reasonable first approximation. This will expand as necessary.
var result = new StringBuilder(maxAllowedLimit);
int totalReadBytes = 0;
using (var stream = await response.Content.ReadAsStreamAsync())
{
    while (totalReadBytes <= maxAllowedLimit)
    {
        int readBytes = await stream.ReadAsync(
            bytes,
            0,
            Math.Min(maxAllowedLimit - totalReadBytes, bytes.Length));

        // We reached the end of the stream
        if (readBytes == 0)
            break;

        totalReadBytes += readBytes;

        int readChars = decoder.GetChars(bytes, 0, readBytes, chars, 0);
        result.Append(chars, 0, readChars);
    }
}

请注意,你可能想要使用HttpCompletionOption.ResponseHeadersRead,否则HttpClient会去下载整个身体。

如果你很乐意限制人物的数量,那么生活会更容易:

string result;
using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
    char[] chars = new char[maxAllowedLimit];
    int read = reader.ReadBlock(chars, 0, chars.Length);
    result = new string(chars, 0, read);
}
© www.soinside.com 2019 - 2024. All rights reserved.