text file: Reading line by line C#

后端 未结 5 411
太阳男子
太阳男子 2021-01-04 19:38

So, let\'s say i have a text file with 20 lines, with on each line different text. i want to be able to have a string that has the first line in it, but when i do NextLine()

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 20:28

    One simple call should do it:

    var fileLines = System.IO.File.ReadAllLines(fileName);
    

    You will want to validate the file exists and of course you still need to watch for blank lines or invalid values but that should give you the basics. To loop over the file you can use the following:

    foreach (var singleLine in fileLines) {
       // process "singleLine" here
    }
    

    One more note - you won't want to do this with large files since it processes everything in memory.

提交回复
热议问题