44 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: 
open System.IO

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

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

Full name: Script.fs
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>
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<_>
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
Next Version Raw view Test code New version

More information

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