read a text file line by line

為{幸葍}努か 提交于 2020-05-19 02:33:00

问题


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.


回答1:


It's all built into StreamReader:

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



回答2:


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


来源:https://stackoverflow.com/questions/18498495/read-a-text-file-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!