In this chapter you will learn:
- What is StringWriter class in C#?
- How to write text in a file using StringWriter class
- Programming Examples and Codes
What is StringWriter class?
StringWriter class is derived from
TextWriter class and it is mainly used to manipulate string rather than files.
StringWriter enables you to write to a string synchronously or asynchronously. You can write a character with
WriteAsync(Char) method and writer string with
WriterAsync(String) method. The text or information written by
StringWriter class is stored inside a
StringWriter is not for writing files on local disk. It is used for manipulate string and it saves information in
How to write text in a file using StringWriter class?
static void Main(string args)
string text = "Hello. This is Line 1 \n Hello. This is Line 2 \nHello This is Line 3";
//Writing string into StringBuilder
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
//Store Data on StringBuilder
StringReader reader = new StringReader(sb.ToString());
//Check to End of File
while (reader.Peek() > -1)
This example demonstrate well StringWriter() and StringReader() Class. String variable text stores a string value and using StringWriter this string value gets stored in StringBuilder. Next using StringReader the data gets displayed on console.
In this chapter you have learned
StringWriter in details with complete programming examples and codes. The next chapter explains StringReader.