43 people like it.

Restartable File.ReadLines

.Net 4.0 added File.ReadLines to view a file as a sequence, but the sequence can only be read once. A simple wrapper with seq{yield!} fixes that.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
open System.IO

// Wrap File.ReadLines() in a seq so it can be read multiple times
let ls = seq { yield! File.ReadLines(@"c:\windows\system.ini") }

Seq.iter (printfn "%s") ls  // OK
Seq.iter (printfn "%s") ls  // OK

// fs Can't be enumerated more than once or Reset
let fs = File.ReadLines(@"c:\windows\system.ini")

Seq.iter (printfn "%s") fs  // OK
Seq.iter (printfn "%s") fs  // Fail!
namespace System
namespace System.IO
val ls : seq<string>

Full name: Script.ls
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
type File =
  static member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload
  static member AppendAllText : path:string * contents:string -> unit + 1 overload
  static member AppendText : path:string -> StreamWriter
  static member Copy : sourceFileName:string * destFileName:string -> unit + 1 overload
  static member Create : path:string -> FileStream + 3 overloads
  static member CreateText : path:string -> StreamWriter
  static member Decrypt : path:string -> unit
  static member Delete : path:string -> unit
  static member Encrypt : path:string -> unit
  static member Exists : path:string -> bool
  ...

Full name: System.IO.File
File.ReadLines(path: string) : System.Collections.Generic.IEnumerable<string>
File.ReadLines(path: string, encoding: System.Text.Encoding) : System.Collections.Generic.IEnumerable<string>
module Seq

from Microsoft.FSharp.Collections
val iter : action:('T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val fs : System.Collections.Generic.IEnumerable<string>

Full name: Script.fs

More information

Link:http://fssnip.net/3C
Posted:6 years ago
Author:Tony Lee
Tags: file , seq