题
什么是写入一个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);
解决方案
不要使用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(...);
}
其他提示
这是最好的方法。其他明智损失的StringBuilder和使用类似以下内容:
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode))
{
sw.WriteLine("dirty world.");
}
//do somthing with ms
}
也许这将是有用的。
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
根据您的使用情况下,它也可能是有意义的只是一个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
如果你想使用像一个StringBuilder,因为它是清洁剂绕过而努力,那么你可以使用像我创建了下面的StringBuilder替代。
它确实不同,最重要的是,它允许访问内部数据,而不必把它组装成一个字符串或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);
});
}
不隶属于 StackOverflow