You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Storing Data

Once you’ve computed the values you need, you will probably want to save that data to disk or in a database. There are numerous ways to store data in .NET, each with varying degrees of performance and ease of use.

File IO

Most .NET IO facilities are based around the abstract System.IO.Stream class, which defines a primitive interface between the stream and the backing store. (Backing store is just a fancy term for “where the data comes from.”) Classes inherit from Stream and add specialized ways to read or write from a particular backing store. For example, MemoryStream is used to read or write data from memory, NetworkStream is used to read or write data from a network connection, FileStream is used to read or write data from a file, and so on.

The simplest way to read or write data from disk is to use the File.ReadAllLines and File.WriteAllLines methods. WriteAllLines takes a file path and a string array of textual data to be written to the file, while ReadAllLines takes a file path and returns the string array of the file’s lines:

> // Solving the fizz buzz problem
open System.IO

let computeFileContents() =
    [| 1 .. 100 |]
                 | x when x % 3 = 0 && x % 5 = 0 -> "FizzBuzz"
                 | x when x % 3 = 0 -> "Fizz"
                 | x when x % 5 = 0 -> "Buzz"
                 | _ -> ".");;

val computeFileContents : unit -> string array

> File.WriteAllLines("FizzBuzzSln.txt", computeFileContents());;
val it : unit = ()

> let fileContents = File.ReadAllLines("FizzBuzzSln.txt");; val fileContents : string ...

The best content for your career. Discover unlimited learning on demand for around $1/day.