read a text file line by line

197 views Asked by At

I need to read data from a text file line by line. Each line contains either a string or an integer. I want to use StreamReader to read line by line from the text file and StreamWriter to write it to a binary file. The "write to binary file" part will be easy. The "read from text file line by line" part is the part I need help with.

2

There are 2 answers

2
Joe Enos On

It's all built into StreamReader:

using (var sr = new StreamReader(myFile))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        // line is the text line
    }
}
0
ismellike On

In c# you can do something like this.

string loc = "idk/where/ever";
using(var sr = new StreamReader(loc))
  using(var sw = new StreamWriter(loc+".tmp"))
    {
     string line; 
        while((line=sr.ReadLine())!=null)
           {
              sw.WriteLine(line);
                //edit it however you want
           }
     }
File.Delete(loc);
File.Move(loc+".tmp",loc);