Skip to content

Allow creating a directory with automatic cleanup without affecting CurrentDirectory #1023

@agc93

Description

@agc93

the IFileSystem.SetCurrentDirectoryToEmptyTemporaryDirectory() helper is effective for testing code that uses Environment.GetCurrentDirectory() but I have testing code that needs temporary directories that I want to clean up on test completion, but using that helper in any test breaks other tests that use Environment.GetCurrentDirectory() and don't expect the temporary path.

More broadly, it would be useful to be able to create temporary directories with IDisposable-based cleanup without affecting the current working directory. I would use DirectoryCleaner directly (since that's what I actually want), but it's internal.

Can we either have DirectoryCleaner make public or provide an equivalent to SetCurrentDirectoryToEmptyTemporaryDirectory() that doesn't affect GetCurrentDirectory()?

At the moment, I'm using this as a workaround, but it feels hacky:

var oldCurrent = Directory.GetCurrentDirectory();
var real = new RealFileSystem();
var prefix = "myPrefix;
var cleaner =
    real.SetCurrentDirectoryToEmptyTemporaryDirectory(prefix: prefix);
var tempPath = real.Path.Combine(real.Directory.GetCurrentDirectory(), real.Path.GetRandomFileName());
Directory.SetCurrentDirectory(oldCurrent); //I don't want this updated, I just want an auto-cleanup-able directory
//do stuff with my temp file but using tempPath itself so I don't actually use GetCurrentDirectory itself
// then when I'm done:
cleaner.Dispose(); // to get the nice auto-cleanup of IDirectoryCleaner

Metadata

Metadata

Assignees

No one assigned

    Labels

    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions