StreamReader reads text files and StreamWriter writes text files. It is under the System.IO namespace. You can probably use this if you have application that requires data to be save as text file such as database logs or system logs.
StreamReader
You can use the following code to read the single line content of a Text file;
private void ReadTxt()
{
string myTxt; using (StreamReader readTxt = new StreamReader(@"C:\\MyTxt.txt")) { myTxt= readTxt .ReadLine(); } MessageBox.Show("Read Text!" + myTxt +, "New Text", MessageBoxButtons.OK);
}
You can use the following code to read multi line content of a Text file.
Then you can save each value in an array of string.
private void ReadMultiLineTxt()
{
string myTxt;
using (StreamReader readTxt = new StreamReader(@"C:\\MyTxt.txt"))
{
while (sr.Peek() >= 0)
{
myTxt= readTxt .ReadLine();
}
}
MessageBox.Show("Read Text!" + myTxt +, "New Text", MessageBoxButtons.OK);
}
StreamWriter
You can use the following code to create and write content of a Text file;
private void WriteTxt()
{
string myTxt; using (StreamWriter writeTxt = new StreamWriter(@"C:\\MyTxt.txt")) { writeTxt .Write("Welcome"); writeTxt .WriteLine("Hello"); writeTxt .WriteLine("World!"); } MessageBox.Show("New Text File Created!", "New Text", MessageBoxButtons.OK);
}
You can use the following code to write and append content of a Text file;
private void WriteAppendTxt()
{
string myTxt; using (StreamWriter writeTxt = new StreamWriter(@"C:\\MyTxt.txt",true)) { writeTxt .WriteLine("Hello"); }
using (StreamWriter writeTxt = new StreamWriter(@"C:\\MyTxt.txt",true)) { writeTxt .WriteLine("World!"); }
MessageBox.Show("New Text File Created!", "New Text", MessageBoxButtons.OK);
}
It's so easy and simple to read and write. You can use my code and play around with it.
No comments:
Post a Comment