F# I/O Libraries
F#'s standard library provides robust support for input and output operations. These libraries leverage the underlying .NET Framework classes for file access, console interaction, and network communication, while offering a more functional and idiomatic F# experience.
Core Concepts and Modules
The primary module for I/O operations in F# is System.IO
, which is accessible directly. F# enhances this with convenience functions and types.
File Operations
Reading and writing to files is a common task. F# offers functions to handle this efficiently.
Reading from Files
You can read the entire content of a file as a string, or read it line by line.
open System.IO
// Read the entire content of a file
let fileContent = File.ReadAllText("myFile.txt")
printfn "%s" fileContent
// Read lines from a file
let lines = File.ReadAllLines("myFile.txt")
for line in lines do
printfn "Line: %s" line
Writing to Files
Writing data to files can be done by appending or overwriting content.
open System.IO
// Write a string to a file, overwriting existing content
File.WriteAllText("output.txt", "This is the first line.\nThis is the second line.")
// Append a string to a file
File.AppendAllText("output.txt", "\nThis line was appended.")
FileNotFoundException
or IOException
using `try...with` blocks for robust applications.
Console Input/Output
Interacting with the console is essential for many command-line applications.
Reading from Console
Console.ReadLine()
reads a line of text from the standard input stream.
open System
printf "Enter your name: "
let name = Console.ReadLine()
printfn "Hello, %s!" name
Writing to Console
printfn
is the idiomatic F# way to write formatted output to the console, followed by a newline. printf
writes without a newline.
open System
let pi = 3.14159
printfn "The value of Pi is approximately %.3f" pi
printf "This is on the same line."
printfn " This is too."
Working with Streams
For more granular control over I/O, you can work directly with streams like StreamReader
and StreamWriter
.
open System.IO
try
use reader = new StreamReader("myFile.txt")
use writer = new StreamWriter("copy.txt")
let mutable line = reader.ReadLine()
while line <> null do
writer.WriteLine(line)
line <- reader.ReadLine()
printfn "File copied successfully."
except
| ex -> printfn "An error occurred: %s" ex.Message
Directory Operations
Managing directories is also part of I/O. The System.IO.Directory
class provides methods for this.
open System.IO
// Get current directory
let currentDirectory = Directory.GetCurrentDirectory()
printfn "Current directory: %s" currentDirectory
// Create a new directory
let newDir = "myNewFolder"
if not (Directory.Exists(newDir)) then
Directory.CreateDirectory(newDir)
printfn "Directory '%s' created." newDir
// List files in a directory
let files = Directory.GetFiles(".")
printfn "Files in current directory:"
for file in files do
printfn "- %s" file
Related API References
System.IO.File
Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in creating FileStream
objects.
System.IO.StreamReader
Implements a TextReader
that reads characters from a byte stream in a particular encoding.
System.IO.StreamWriter
Implements a TextWriter
for writing characters to a stream in a particular encoding.
System.Console
Provides access to the standard input, output, and error streams for console applications.