nati
nati

Reputation: 101

How to read/write one line at a time from a text file in C#

I want to read from the file "hello.txt" on line each time and then write this line to "bye.text" and to the screen. How can I do this? The only funcs I see in "File" are:

Upvotes: 1

Views: 7358

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243041

As Jack says, you need to use the StreamWriter and StreamReader types if you want to work with files (or any other streams) using line-by-line functions. Just use the constructor like this:

open System.IO

let addLine (line:string) =     
  use wr = StreamWriter("D:\\temp\\test.txt", true)
  wr.WriteLine(line)

Here, we're using an overload of the StreamWriter constructor that takes the path (as a string) and boolean specifying that we want to append to an existing file. Also note that I'm using use keyword to make sure that the file is closed when addLine completes.

To read content as a sequence of lines, you can use StreamReader similarly - create an instance of the type using constructor and then use ReadLine method until you get null as a result.

Upvotes: 10

Jack P.
Jack P.

Reputation: 11525

The methods in the System.IO.File class only support reading/writing the entire file. If you want a more granular approach (e.g., reading/writing line-by-line) you need to use something like StreamReader and StreamWriter.

Upvotes: 3

Related Questions