C# 如何将blob数据转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14320270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:25:22  来源:igfitidea点击:

How to convert blob data to string?

c#asp.net

提问by mck

I am using the following function to convert binary data to text:

我正在使用以下函数将二进制数据转换为文本:

public string BinaryToText(byte[] data)
{
     MemoryStream stream = new MemoryStream(data);
     StreamReader reader = new StreamReader(stream, encoding.UTF8);
     string text = reader.ReadTod();
     return text;
}

But I get an OutOfMemoryExceptionfor 30Mb data.

但是我得到了一个OutOfMemoryException30Mb 的数据。

How can I solve this problem and convert data larger than 100Mb, using this or any better method?

如何使用此方法或任何更好的方法解决此问题并转换大于 100Mb 的数据?

采纳答案by Matthew Watson

Try this instead:

试试这个:

public string BinaryToText(byte[] data)
{
    return Encoding.UTF8.GetString(data);
}

It will consume less memory. If it stillruns out of memory, you'll need to read it in chunks - but how you are using the data will determine if that is possible. What are you doing with the returned string?

它会消耗更少的内存。如果它仍然耗尽内存,您需要分块读取它 - 但是您如何使用数据将决定这是否可行。你用返回的字符串做什么?

Also I will reiterate my earlier question: Is the input data reallyUTF8 data?

我还要重申我之前的问题:输入数据真的是UTF8 数据吗?

If you canhandle the data being returned as multiple strings, you can do something like this:

如果您可以处理作为多个字符串返回的数据,您可以执行以下操作:

public IEnumerable<string> BinaryToStrings(byte[] data, int maxStringLength)
{
    var buffer = new char[maxStringLength];

    using (MemoryStream stream = new MemoryStream(data))
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    {
        while (true)
        {
            int count = reader.Read(buffer, 0, maxStringLength);

            if (count == 0)
            {
                break;
            }

            yield return new string(buffer, 0, count);
        }
    }
}

Then you can call that in a foreach loop like so:

然后你可以像这样在 foreach 循环中调用它:

foreach (string chunk in BinaryToStrings(data, 1024))
{
    // Do something with 'chunk'...
}