- 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 Write(Char) or WriteAsync(Char) method and writer string with Write(String) or WriterAsync(String) method. The text or information written by StringWriter class is stored inside a StringBuilder.
Note: StringWriter is not for writing files on local disk. It is used for manipulate string and it saves information in StringBuilder.
How to write text in a file using StringWriter class?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace StringWriter_Class
{
class Program
{
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
writer.WriteLine(text);
writer.Flush();
writer.Close();
//Read Entry
StringReader reader = new StringReader(sb.ToString());
//Check to End of File
while (reader.Peek() > -1)
{
Console.WriteLine(reader.ReadLine());
}
}
}
}
Explanation
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.
Summary
In this chapter you have learned StringWriter in details with complete programming examples and codes. The next chapter explains StringReader.
In this chapter you will learn: