C# 将 StringBuilder 写入流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2236432/
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
Write StringBuilder to Stream
提问by Andy Joiner
What is the best method of writing a StringBuilder to a System.IO.Stream?
将 StringBuilder 写入 System.IO.Stream 的最佳方法是什么?
I am currently doing:
我目前正在做:
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);
采纳答案by Neil Barnwell
Don't use a StringBuilder, if you're writing to a stream, do just that with a StreamWriter:
不要使用 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(...);
}
回答by particle
That is the best method. Other wise loss the StringBuilder and use something like following:
那是最好的方法。其他明智的损失 StringBuilder 并使用以下内容:
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode))
{
sw.WriteLine("dirty world.");
}
//do somthing with ms
}
回答by Chris Moschini
Depending on your use case it may also make sense to just start with a StringWriter:
根据您的用例,从 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
回答by Developer
Perhaps it will be usefull.
也许它会很有用。
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
回答by AnthonyVO
If you want to use something like a StringBuilder because it is cleaner to pass around and work with, then you can use something like the following StringBuilder alternate I created.
如果您想使用 StringBuilder 之类的东西,因为它可以更清晰地传递和使用,那么您可以使用类似于我创建的以下 StringBuilder 替代品。
The most important thing it does different is that it allows access to the internal data without having to assemble it into a String or ByteArray first. This means you don't have to double up the memory requirements and risk trying to allocate a contiguous chunk of memory that fits your entire object.
它所做的最重要的不同之处在于它允许访问内部数据,而无需先将其组装成 String 或 ByteArray。这意味着您不必将内存需求加倍,也不必冒险尝试分配适合整个对象的连续内存块。
NOTE: I am sure there are better options then using a List<string>()
internally but this was simple and proved to be good enough for my purposes.
注意:我确信有比在List<string>()
内部使用 a 更好的选择,但这很简单,并且证明对我的目的来说已经足够了。
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);
}
}
Now you can dump the entire contents to file using the following code.
现在您可以使用以下代码将整个内容转储到文件中。
var stringData = new StringBuilderEx();
stringData.Append("Add lots of data");
using (StreamWriter file = new System.IO.StreamWriter(localFilename))
{
stringData.ForEach((data) =>
{
file.Write(data);
});
}