Reputation: 101
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
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
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