从非常大的 stringbuilder 获取 UTF8.GetBytes

Get UTF8.GetBytes from very large stringbuilder

我有一个长度为 1,539,121,968 的 StringBuilder。在其上调用 StringBuilder .ToString() 时失败并返回 OutOfMemoryException。我尝试创建一个 char 数组,但不允许创建这么大的数组。

我需要将它存储为 UTF8 格式的字节数组。可能吗?

我建议查看流的文档。因为这可能会有所帮助。

另一种方法是将其拆分。至于你最后的评论说你希望将它存储为 ByteArray 和 UTF8 你需要一个 char[] 否则你会丢失你的编码。我建议将它拆分成许多更小的字符串(或 char[]s),存储在可以轻松重建的单独对象中。这样的东西可能就足够了,创建许多 StringSlices:

public class StringSlice()
{
     public Str {get;}
     public Index {get;}
     public StringSlice(string str, int index)
         {
              this.Str = str;
              this.Index = index;
         }

     public static List<string> ReconstructString(IEnumerable<StringSlice> parts)
         {
              //Sort input by index return list with new strings in order. Probably have to use a buffer on the disc so as not to breach 2GB obj limit.
         }
}

本质上,您在这里所做的与 Internet 数据包的拆分和重构方式类似。我不完全确定我是否已经回答了您的问题,但希望这能对您有所帮助。