ZetCode

F# directories and paths

last modified December 3, 2026

In this article we work with paths and directories in F#.

A path is a string that locates a file or directory, such as project/src/Main.fs. The .NET Path class builds and takes apart paths as strings, without touching the disk. The Directory class creates, lists and deletes directories, and FileInfo and DirectoryInfo describe one file or directory with its size and dates. Reading and writing the content of files is covered in F# file I/O.

Building paths

Paths should be joined with Path.Combine rather than with string concatenation. It inserts the separator of the operating system: a slash on Linux and macOS, a backslash on Windows.

combine.fsx
open System.IO

let folder = "project"
let file = Path.Combine(folder, "src", "Main.fs")

printfn "%s" file
printfn "separator: %c" Path.DirectorySeparatorChar

printfn "%s" (Path.Combine("project/", "docs"))
printfn "%s" (Path.Combine("project", "/etc/hosts"))
printfn "%s" (Path.Join("project", "/etc/hosts"))

We build paths from several parts.

printfn "%s" (Path.Combine("project/", "docs"))

Combine adds a separator only where one is missing, so a trailing slash does not produce a double slash.

printfn "%s" (Path.Combine("project", "/etc/hosts"))
printfn "%s" (Path.Join("project", "/etc/hosts"))

When a later part is an absolute path, Combine drops everything before it. This matters when a part comes from the user. Path.Join simply joins the parts, whatever they contain.

λ dotnet fsi combine.fsx
project/src/Main.fs
separator: /
project/docs
/etc/hosts
project/etc/hosts

Parts of a path

The Path class takes a path apart into the directory, the file name and the extension. The methods work on the string only, so the file does not have to exist.

parts.fsx
open System.IO

let path = "project/docs/guide.draft.md"

printfn "directory: %s" (Path.GetDirectoryName path)
printfn "file name: %s" (Path.GetFileName path)
printfn "without extension: %s" (Path.GetFileNameWithoutExtension path)
printfn "extension: %s" (Path.GetExtension path)
printfn "has extension: %b" (Path.HasExtension path)
printfn "changed: %s" (Path.ChangeExtension(path, ".html"))

printfn "rooted: %b %b" (Path.IsPathRooted path) (Path.IsPathRooted "/var/log")

We take apart a path to a Markdown file with two dots in its name.

printfn "extension: %s" (Path.GetExtension path)

The extension is the part after the last dot, including the dot. The rest of the name, guide.draft, keeps its inner dot.

printfn "rooted: %b %b" (Path.IsPathRooted path) (Path.IsPathRooted "/var/log")

A rooted path starts at the root of the file system; other paths are relative to the current directory.

λ dotnet fsi parts.fsx
directory: project/docs
file name: guide.draft.md
without extension: guide.draft
extension: .md
has extension: true
changed: project/docs/guide.draft.html
rooted: false true

Full and relative paths

Path.GetFullPath turns a relative path into an absolute one and removes . and .. parts. Path.GetRelativePath does the opposite: it describes one path relative to another.

fullpath.fsx
open System.IO

let home = "/home/lucia"

printfn "%s" (Path.GetFullPath("notes/todo.txt", home))
printfn "%s" (Path.GetFullPath("../peter/./photos", home))
printfn "%s" (Path.GetFullPath "/var/log/../tmp/report.txt")

printfn "%s" (Path.GetRelativePath(home, "/home/lucia/music/jazz"))
printfn "%s" (Path.GetRelativePath("/home/lucia/music", "/home/peter"))

let here = Path.Combine(__SOURCE_DIRECTORY__, "fullpath.fsx")
printfn "script found: %b" (File.Exists here)

The second argument of GetFullPath is the base directory. With one argument, the base is the current directory, which depends on where the program is started; the examples use fixed bases so that the output is the same everywhere.

let here = Path.Combine(__SOURCE_DIRECTORY__, "fullpath.fsx")

__SOURCE_DIRECTORY__ is the directory of the script file. A script that reads a data file stored next to it should build the path from it; then the script also works when it is run from another directory.

λ dotnet fsi fullpath.fsx
/home/lucia/notes/todo.txt
/home/peter/photos
/var/tmp/report.txt
music/jazz
../../peter
script found: true

Creating directories

Directory.CreateDirectory creates a directory together with any missing parent directories. If the directory already exists, it does nothing. The script below creates a small project that the next sections work with.

create.fsx
open System.IO

let files =
    [ "project/README.md", "# Weather station\n"
      "project/notes.txt", "Calibrate the sensor.\nOrder a new cable.\n"
      "project/src/Main.fs", "printfn \"Reading sensors\"\n"
      "project/src/Sensors.fs", "module Sensors\n\nlet read () = 21.5\n"
      "project/docs/guide.md", "# Guide\n\nConnect the cable to port A.\n"
      "project/docs/old/guide.md", "# Guide\n" ]

for path, content in files do
    Directory.CreateDirectory(Path.GetDirectoryName path) |> ignore
    File.WriteAllText(path, content)

printfn "project exists: %b" (Directory.Exists "project")
printfn "docs/old exists: %b" (Directory.Exists "project/docs/old")
printfn "guide is a directory: %b" (Directory.Exists "project/docs/guide.md")

Each file is written after its directory has been created.

Directory.CreateDirectory(Path.GetDirectoryName path) |> ignore

CreateDirectory returns a DirectoryInfo for the new directory, which we do not need, so it is passed to ignore. For project/docs/old/guide.md it creates docs and old in one call.

printfn "guide is a directory: %b" (Directory.Exists "project/docs/guide.md")

Directory.Exists is false for a file, and File.Exists is false for a directory.

λ dotnet fsi create.fsx
project exists: true
docs/old exists: true
guide is a directory: false

Listing a directory

Directory.GetFiles and Directory.GetDirectories return the paths of the entries of one directory. A search pattern such as *.md selects entries by name.

listing.fsx
open System.IO

let root = "project"

printfn "directories:"
for d in Directory.GetDirectories root |> Array.sort do
    printfn "  %s" (Path.GetFileName d)

printfn "files:"
for f in Directory.GetFiles root |> Array.sort do
    printfn "  %s" (Path.GetFileName f)

printfn "markdown: %A" (Directory.GetFiles(root, "*.md"))

The script lists the top level of the project.

for d in Directory.GetDirectories root |> Array.sort do

The order of the entries depends on the file system and is not guaranteed, so we sort them. The returned paths include the directory we listed; Path.GetFileName keeps only the last part.

λ dotnet fsi listing.fsx
directories:
  docs
  src
files:
  README.md
  notes.txt
markdown: [|"project/README.md"|]

Searching recursively

Directory.EnumerateFiles with SearchOption.AllDirectories also looks into subdirectories. It returns a lazy sequence, so the search can stop early, while GetFiles collects all paths first.

search.fsx
open System.IO

let root = "project"

let markdown =
    Directory.EnumerateFiles(root, "*.md", SearchOption.AllDirectories)
    |> Seq.map (fun p -> Path.GetRelativePath(root, p))
    |> Seq.sort
    |> Seq.toList

printfn "%d markdown files" markdown.Length
for p in markdown do
    printfn "  %s" p

let cable =
    Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
    |> Seq.filter (fun p -> File.ReadAllText(p).Contains "cable")
    |> Seq.map (fun p -> Path.GetRelativePath(root, p))
    |> Seq.sort

printfn "files mentioning a cable: %A" (Seq.toList cable)

We find all Markdown files and all files that contain a word.

|> Seq.map (fun p -> Path.GetRelativePath(root, p))

The paths are shown relative to the project directory, which is shorter and does not depend on where the project is.

λ dotnet fsi search.fsx
3 markdown files
  README.md
  docs/guide.md
  docs/old/guide.md
files mentioning a cable: ["docs/guide.md"; "notes.txt"]

FileInfo and DirectoryInfo

A FileInfo object describes a file: its name, extension, size in bytes, and creation and modification dates. A DirectoryInfo describes a directory and lists its entries as FileInfo objects.

info.fsx
open System.IO

let readme = FileInfo "project/README.md"

printfn "%s: %d bytes, extension %s" readme.Name readme.Length readme.Extension
printfn "in directory: %s" readme.Directory.Name
printfn "read-only: %b" readme.IsReadOnly

let project = DirectoryInfo "project"
let all = project.GetFiles("*", SearchOption.AllDirectories)

printfn "total: %d files, %d bytes" all.Length (all |> Array.sumBy (fun f -> f.Length))

all
|> Array.groupBy (fun f -> f.Extension)
|> Array.sortBy fst
|> Array.iter (fun (ext, fs) ->
    printfn "%-4s %d files %4d bytes" ext fs.Length (fs |> Array.sumBy (fun f -> f.Length)))

The script prints facts about one file and a summary of the project by extension.

printfn "%s: %d bytes, extension %s" readme.Name readme.Length readme.Extension

Length is an int64, because files may be larger than 2 GB. The dates, CreationTime and LastWriteTime, are left out here because they change with each run.

λ dotnet fsi info.fsx
README.md: 18 bytes, extension .md
in directory: project
read-only: false
total: 6 files, 166 bytes
.fs  2 files   61 bytes
.md  3 files   64 bytes
.txt 1 files   41 bytes

Copying, moving and deleting

File.Copy, File.Move and File.Delete work on single files. Directory.Move renames a directory, and Directory.Delete with true deletes a directory with all its content.

manage.fsx
open System.IO

let show () =
    Directory.EnumerateFiles("project", "*", SearchOption.AllDirectories)
    |> Seq.map (fun p -> Path.GetRelativePath("project", p))
    |> Seq.sort
    |> String.concat " "
    |> printfn "%s"

show ()

File.Copy("project/notes.txt", "project/notes.bak", true)
File.Move("project/notes.txt", "project/docs/notes.txt")
Directory.Delete("project/docs/old", true)
File.Delete "project/notes.bak"
File.Delete "project/missing.txt"

show ()

The script reorganizes the project and prints its files before and after.

File.Copy("project/notes.txt", "project/notes.bak", true)

The last argument allows Copy to replace an existing file; without it, copying over a file throws an IOException. Move also renames: the target may be in the same directory with a new name.

File.Delete "project/missing.txt"

Deleting a file that does not exist is not an error. Deleting a directory that does not exist is, and Directory.Delete without true refuses to delete a directory that is not empty.

λ dotnet fsi manage.fsx
README.md docs/guide.md docs/old/guide.md notes.txt src/Main.fs src/Sensors.fs
README.md docs/guide.md docs/notes.txt src/Main.fs src/Sensors.fs

Printing a directory tree

The last program prints a directory as a tree with the size of each file. A recursive function handles one directory and calls itself for each subdirectory.

tree.fsx
open System.IO

let rec printTree (dir: DirectoryInfo) (indent: string) =
    let dirs = dir.GetDirectories() |> Array.sortBy (fun d -> d.Name)
    let files = dir.GetFiles() |> Array.sortBy (fun f -> f.Name)

    let mutable total = 0L

    for d in dirs do
        printfn "%s%s/" indent d.Name
        total <- total + printTree d (indent + "    ")

    for f in files do
        printfn "%s%s (%d B)" indent f.Name f.Length
        total <- total + f.Length

    total

let root = DirectoryInfo "project"
printfn "%s/" root.Name
let size = printTree root "    "
printfn "%d bytes" size

The function prints the subdirectories first, then the files, and returns the size of everything below the directory.

total <- total + printTree d (indent + "    ")

Each level of the tree is indented by four more spaces. The recursive call prints the subdirectory and returns its size, which is added to the size of the current directory.

λ dotnet fsi tree.fsx
project/
    docs/
        guide.md (38 B)
        notes.txt (41 B)
    src/
        Main.fs (26 B)
        Sensors.fs (35 B)
    README.md (18 B)
158 bytes

Source

.NET documentation: Common I/O tasks

.NET API: Path class

In this article we have built and taken apart paths, resolved full and relative paths, created directories, listed and searched them, read file sizes with FileInfo, copied, moved and deleted files and printed a directory tree. Reading and writing files is covered in F# file I/O, and file dates can be formatted as shown in F# dates and times.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.