将StringBuilder写入stream
写一个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,如果你正在写一个stream,就用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替代我创build的东西。
它所做的最重要的不同之处在于,它允许访问内部数据,而无需首先将其组装到string或ByteArray中。 这意味着您不必将内存需求加倍,并且可能会尝试分配适合整个对象的连续内存块。
注:我相信有更好的select,然后使用List<string>()
内部,但这是很简单的,certificate是足够我的目的。
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); }); }