12 Temmuz 2017 Çarşamba

c# StreamReader sr = new StreamReader

Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readMeText = readtext.ReadLine();
}
Notes:
  • You can use readtext.Close() instead of using, but it will not close file/reader/writer in case of exceptions
  • Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
  • Missing using/Close is very common reason of "why data is not written to file".

String line;try 
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");

//Read the first line of text
line = sr.ReadLine();

//Continue to read until you reach end of file
while (line != null) 
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}

//close the file
sr.Close();
Console.ReadLine();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
   finally 
{
Console.WriteLine("Executing finally block.");
}