What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?
I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.
In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.
System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());
You still have access to StreamWriter
:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText
method.
System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());
No need for a StringBuilder
:
string path = @"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder
to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write
Method (String) (.NET Framework 1.1)
Writing Text to a File (.NET Framework 1.1)