CodeGo.net>写StringBuilder流

将StringBuilder写入System.IO.Stream的最佳方法是什么?

我目前正在做:

StringBuilder message = new StringBuilder("All your base");
message.Append(" are belong to us");

System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Text.ASCIIEncoding encoding = new ASCIIEncoding();
stream.Write(encoder.GetBytes(message.ToString()), 0, message.Length);
Andy Joiner asked 2020-02-02T18:29:57Z
5个解决方案
78 votes

不要使用StringBuilder,如果要写入流,请使用StreamWriter来做到这一点:

using (var memoryStream = new MemoryStream())
using (var writer = new StreamWriter(memoryStream ))
{
    // Various for loops etc as necessary that will ultimately do this:
    writer.Write(...);
}
Neil Barnwell answered 2020-02-02T18:30:10Z
14 votes

那是最好的方法。 其他明智的做法是丢失StringBuilder并使用如下所示的内容:

using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode))
    {
        sw.WriteLine("dirty world.");
    }
    //do somthing with ms
}
particle answered 2020-02-02T18:30:30Z
6 votes

也许会有用。

var sb= new StringBuilder("All your money");
sb.Append(" are belong to us, dude.");
var myString = sb.ToString();
var myByteArray = System.Text.Encoding.UTF8.GetBytes(myString);
var ms = new MemoryStream(myByteArray);
// Do what you need with MemoryStream
Developer answered 2020-02-02T18:30:50Z
5 votes

根据您的用例,以StringWriter开头也可能很有意义:

StringBuilder sb = null;

// StringWriter - a TextWriter backed by a StringBuilder
using (var writer = new StringWriter())
{
    writer.WriteLine("Blah");
    . . .
    sb = writer.GetStringBuilder(); // Get the backing StringBuilder out
}

// Do whatever you want with the StringBuilder
Chris Moschini answered 2020-02-02T18:31:10Z
0 votes

如果您想使用诸如StringBuilder之类的东西,因为它更易于传递和使用,那么您可以使用类似于我创建的以下StringBuilder之类的东西。

它所做的最重要的变化是,它允许访问内部数据,而不必首先将其组装为String或ByteArray。 这意味着您不必加倍内存需求,也不必尝试分配适合您整个对象的连续内存块。

注意:我敢肯定,与在内部使用List<string>()相比,还有其他更好的选择,但这很简单,事实证明对于我的目的已经足够了。

public class StringBuilderEx
{
    List<string> data = new List<string>();
    public void Append(string input)
    {
        data.Add(input);
    }
    public void AppendLine(string input)
    {
        data.Add(input + "\n");
    }
    public void AppendLine()
    {
        data.Add("\n");
    }

    /// <summary>
    /// Copies all data to a String.
    /// Warning: Will fail with an OutOfMemoryException if the data is too
    /// large to fit into a single contiguous string.
    /// </summary>
    public override string ToString()
    {
        return String.Join("", data);
    }

    /// <summary>
    /// Process Each section of the data in place.   This avoids the
    /// memory pressure of exporting everything to another contiguous
    /// block of memory before processing.
    /// </summary>
    public void ForEach(Action<string> processData)
    {
        foreach (string item in data)
            processData(item);
    }
}

现在,您可以使用以下代码将全部内容转储到文件中。

var stringData = new StringBuilderEx();
stringData.Append("Add lots of data");

using (StreamWriter file = new System.IO.StreamWriter(localFilename))
{
    stringData.ForEach((data) =>
    {
        file.Write(data);
    });
}
AnthonyVO answered 2020-02-02T18:31:44Z
translate from https://stackoverflow.com:/questions/2236432/write-stringbuilder-to-stream