Introduction

File I/O (Input/Output) is a fundamental aspect of programming that allows you to read from and write to files. In F#, you can perform file I/O operations using the System.IO namespace, which provides various classes and methods to handle files and directories.

Key Concepts

  • Reading Files: Extracting data from a file.
  • Writing Files: Saving data to a file.
  • File Streams: Handling large files efficiently.
  • File and Directory Operations: Creating, deleting, and managing files and directories.

Reading Files

Reading All Text from a File

To read all text from a file, you can use the File.ReadAllText method.

open System.IO

let readTextFromFile (filePath: string) =
    try
        let text = File.ReadAllText(filePath)
        printfn "File content:\n%s" text
    with
    | :? FileNotFoundException -> printfn "File not found."
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
readTextFromFile "example.txt"

Reading Lines from a File

To read lines from a file, you can use the File.ReadAllLines method.

open System.IO

let readLinesFromFile (filePath: string) =
    try
        let lines = File.ReadAllLines(filePath)
        lines |> Array.iter (printfn "%s")
    with
    | :? FileNotFoundException -> printfn "File not found."
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
readLinesFromFile "example.txt"

Writing Files

Writing Text to a File

To write text to a file, you can use the File.WriteAllText method.

open System.IO

let writeTextToFile (filePath: string) (content: string) =
    try
        File.WriteAllText(filePath, content)
        printfn "Text written to file successfully."
    with
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
writeTextToFile "example.txt" "Hello, F# World!"

Writing Lines to a File

To write lines to a file, you can use the File.WriteAllLines method.

open System.IO

let writeLinesToFile (filePath: string) (lines: string[]) =
    try
        File.WriteAllLines(filePath, lines)
        printfn "Lines written to file successfully."
    with
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
writeLinesToFile "example.txt" [| "Line 1"; "Line 2"; "Line 3" |]

File Streams

Reading from a File Stream

For large files, using file streams can be more efficient. You can use the StreamReader class to read from a file stream.

open System.IO

let readFromFileStream (filePath: string) =
    try
        use streamReader = new StreamReader(filePath)
        let content = streamReader.ReadToEnd()
        printfn "File content:\n%s" content
    with
    | :? FileNotFoundException -> printfn "File not found."
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
readFromFileStream "example.txt"

Writing to a File Stream

You can use the StreamWriter class to write to a file stream.

open System.IO

let writeToFileStream (filePath: string) (content: string) =
    try
        use streamWriter = new StreamWriter(filePath)
        streamWriter.Write(content)
        printfn "Text written to file successfully."
    with
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
writeToFileStream "example.txt" "Hello, F# World!"

File and Directory Operations

Creating a Directory

To create a directory, you can use the Directory.CreateDirectory method.

open System.IO

let createDirectory (dirPath: string) =
    try
        Directory.CreateDirectory(dirPath) |> ignore
        printfn "Directory created successfully."
    with
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
createDirectory "exampleDir"

Deleting a File

To delete a file, you can use the File.Delete method.

open System.IO

let deleteFile (filePath: string) =
    try
        File.Delete(filePath)
        printfn "File deleted successfully."
    with
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
deleteFile "example.txt"

Practical Exercises

Exercise 1: Reading and Writing Text Files

  1. Create a function copyFile that reads the content of a file and writes it to another file.
  2. Ensure the function handles exceptions appropriately.
open System.IO

let copyFile (sourcePath: string) (destinationPath: string) =
    try
        let content = File.ReadAllText(sourcePath)
        File.WriteAllText(destinationPath, content)
        printfn "File copied successfully."
    with
    | :? FileNotFoundException -> printfn "Source file not found."
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
copyFile "source.txt" "destination.txt"

Exercise 2: Listing Files in a Directory

  1. Create a function listFiles that lists all files in a given directory.
  2. Ensure the function handles exceptions appropriately.
open System.IO

let listFiles (dirPath: string) =
    try
        let files = Directory.GetFiles(dirPath)
        files |> Array.iter (printfn "%s")
    with
    | :? DirectoryNotFoundException -> printfn "Directory not found."
    | ex -> printfn "An error occurred: %s" (ex.Message)

// Example usage
listFiles "exampleDir"

Summary

In this section, you learned how to perform basic file I/O operations in F#. You explored reading and writing text files, using file streams for efficient file handling, and performing file and directory operations. These skills are essential for managing data in real-world applications. In the next module, you will delve into more advanced data access and manipulation techniques.

© Copyright 2024. All rights reserved