如何BLOB数据转换为字符串? [英] How to convert blob data to string?

查看:206
本文介绍了如何BLOB数据转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的函数将二进制数据转换为文本

I am using 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;
 }

的System.OutOfMemoryException 显示为30MB的数据。如何解决这个问题,转换较大然后使用这个或任何更好的方法100Mb的数据?

But System.OutOfMemoryException is shown for 30Mb data. How to solve this problem and convert larger then 100Mb data using this or any better method?

推荐答案

试试这个:

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

这将消耗更少的内存。如果是的还是的内存用完,你需要以块的形式读它 - 但你如何使用数据将决定是否这是可能的。什么是你在返回的字符串干什么呢?

It will consume less memory. If it still runs 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?

另外,我将重申我刚才的问题:?是输入数据的真正的UTF8数据

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

如果您的可以的处理数据被返回多个字符串,你可以做这样的事情:

If you can handle 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);
        }
    }
}

然后就可以调用,在foreach循环像这样:

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

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

这篇关于如何BLOB数据转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆