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


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: