System.IO.Abstractions.Extensions icon indicating copy to clipboard operation
System.IO.Abstractions.Extensions copied to clipboard

Convenience functionality on top of System.IO.Abstractions

System.IO.Abstractions.Extensions NuGet Continuous Integration Renovate enabled

Convenience functionality on top of System.IO.Abstractions

dotnet add package TestableIO.System.IO.Abstractions.Extensions

Examples

CurrentDirectory extension

var fs = new FileSystem();

//with extension
var current = fs.CurrentDirectory();

//without extension
var current =  fs.DirectoryInfo.FromDirectoryName(fs.Directory.GetCurrentDirectory());

SubDirectory extension

var current = new FileSystem().CurrentDirectory();

//create a "temp" subdirectory with extension
current.SubDirectory("temp").Create();

//create a "temp" subdirectory without extension
current.FileSystem.DirectoryInfo.FromDirectoryName(current.FileSystem.Path.Combine(current.FullName, "temp")).Create();

File extension

var current = new FileSystem().CurrentDirectory();

//create a "test.txt" file with extension
using (var stream = current.File("test.txt").Create())
    stream.Dispose();

//create a "test.txt" file without extension
using (var stream = current.FileSystem.FileInfo.FromFileName(current.FileSystem.Path.Combine(current.FullName, "test.txt")).Create())
    stream.Dispose();

Automatic cleanup with Disposable extensions

Use CreateDisposableDirectory or CreateDisposableFile to create a IDirectoryInfo or IFileInfo that's automatically deleted when the returned IDisposable is disposed.

var fs = new FileSystem();

//with extension
using (fs.CreateDisposableDirectory(out IDirectoryInfo dir))
{
    Console.WriteLine($"This directory will be deleted when control leaves the using block: '{dir.FullName}'");
}

//without extension
var temp = fs.Path.GetTempPath();
var fileName = fs.Path.GetRandomFileName();
var path = fs.Path.Combine(temp, fileName);

try
{
    IDirectoryInfo dir = fs.Directory.CreateDirectory(path);
    Console.WriteLine($"This directory will be deleted in the finally block: '{dir.FullName}'");
}
finally
{
    fs.Directory.Delete(path, recursive: true);
}

IDirectoryInfo.CopyTo extension

var fs = new FileSystem();
var current = fs.CurrentDirectory();

//source
var source =  current.SubDirectory("source");
source.Create(); //make sure the source directory exists

//destination
var dest = current.SubDirectory("destination");

//copy
source.CopyTo(dest, recursive: true);