Reading and writing data using StreamReader and StreamWriter classes
This code snippet shows Reading and writing data using StreamReader and StreamWriter classes.
We are using File class to create a text file so that we can read and write the data to that text file. StreamReader class is used to read the data from the text file and StreamWriter class is used to write the data to the text file.
We are using File class to create a text file so that we can read and write the data to that text file. StreamReader class is used to read the data from the text file and StreamWriter class is used to write the data to the text file.
// Create a new file to work with
FileStream fsOut = File.Create(Server.MapPath("test.txt"));
// Create a StreamWriter to handle writing
StreamWriter swWriter = new StreamWriter(fsOut);
swWriter.WriteLine("Hello World !!!");
swWriter.WriteLine("How are you?");
swWriter.Flush();
swWriter.Close();
fsOut.Close();
//Read the file data
FileStream fsIn = File.OpenRead(Server.MapPath("test.txt"));
// Create a StreamReader to handle reading
StreamReader sReader = new StreamReader(fsIn);
StringBuilder sb = new StringBuilder();
while (sReader.Peek() > -1) //Reads the data
{
sb.AppendLine(sReader.ReadLine());
}
Response.Write(sb.ToString());
sReader.Close();
fsIn.Close();