United Kingdom: +44 (0)208 088 8978

Organizing files with F#

We're hiring Software Developers

Click here to find out more

Organizing a folder full of files and subfolders can be a very mundane and time-consuming task. We can make use of F# and .NET to automate these tedious tasks and make our lives easier.

Let's say we have a folder containing a couple of files, these files can have different extensions like .pdf, .doc etc. For our purposes, we want to move the PDF files into their own folder. We will make use of the System.IO namespace in .NET which will provide us with ways of manipulating files and folders along with a method for compressing.

Note: This will be done in a fsx file that can be run with dotnet fsi or or VSC if you have the ionide extension

open System.IO
open System.IO.Compression

Create directory

Let's create a folder for storing the PDF files

let targetFolder = Directory.CreateDirectory("pdf-folder")

Move multiple files with extension

Let's get the paths for the PDF files by getting the current folder (where the files exist) and make sure we only get the ones with the ".pdf" extension

let sourceDirectory = Directory.GetCurrentDirectory()

let pdfFiles = Directory.GetFiles(sourceDirectory, $"*.pdf")

Now you can move the files by iterating over the array of PDF paths

pdfFiles
|> Array.iter (fun filePath ->
    let fileName = Path.GetFileName(filePath)
    let targetFilePath = Path.Combine(targetFolder.FullName, fileName)

    if File.Exists(targetFilePath) then
        printfn $"File already exists: {targetFilePath}"
    else
        File.Move(filePath, targetFilePath))

Rename files

It is also possible to rename these files. When we iterate we can remove the extension and append a different string

pdfFiles
|> Array.iter (fun filePath ->
    let fileName = Path.GetFileNameWithoutExtension(filePath)
    let targetFilePath = Path.Combine(targetFolder.FullName, fileName + "_new.pdf")

    if File.Exists(targetFilePath) then
        printfn $"Archive file already exists: {targetFilePath}"
    else
        File.Move(filePath, targetFilePath))

You can make use of diffent methods Path provides such as Path.GetExtension to create your own ways of renaming the files

Compress

Lastly, we can make use of System.IO.Compression to compress these files

let zipFilePath = "./archive.zip"

if File.Exists(zipFilePath) then
    printfn $"Archive file already exists: {zipFilePath}"
else
    ZipFile.CreateFromDirectory(targetFolder.FullName, zipFilePath)

Conclusion

We learned how to move files, rename and compress them. We automated a rather tedious and mundane task making organizing files easier 🙂