Search code examples
c#.netfile-iowindows-cestringbuilder

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?


I have to use StringBuilder instead of a List of strings because of being stuck with .NET 1.1 for this project.

I want to write a series of debug messages I've written to a file to study at my leisure, as there is too much to see on the screen (the MessageBox doesn't have scrollbars). Some of the easy ways to write a file don't seem to be available in .NET 1.1. I also don't have access to Environment.Newline to cleanly separate the lines I append (AppendLine is not available in this archaic version of StringBuilder, either).

What is the easiest way in .NET 1.1 (C#) to write out the contents of the StringBuilder to a file? There is no "C" drive on the handheld device, so I reckon I will have to write it to "\hereIAm.txt" or something.


Solution

  • 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());