Skip to content

[API Proposal]: Creating an empty temporary directory #72881

@eerhardt

Description

@eerhardt

Background and motivation

When dealing with temporary files, especially with more than one, we would like to create our own folder and place them inside. There are several ways to achieve this but for convenience and for completion of the existing Path.GetTempFileName there should be an official API for this.

This has been requested a few times before (#2048, #23538, #31243). #2048 is a large higher-level API proposal for an object model of working with temporary files. To make forward progress here, for 7.0 we should add a simple API that creates a new, empty temp directory. This would correspond with other Unix POSIX work we've been doing in 7.0 (#68770, #67837).

On Unix, this would use mkdtemp, just like how Path.GetTempFileName uses mkstemps. On Windows, this API would generate a new random directory name (possibly using Guid.NewGuid) guaranteeing that the new directory was freshly created.

API Proposal

namespace System.IO;

public static class Path
{
    public static string GetTempPath();
    public static string GetTempFileName();

+    /// <summary>
+    /// Creates a uniquely named, empty directory and returns the full path of that directory. 
+    /// </summary>
+    public static string CreateTemporaryDirectory();
}

API Usage

string tempDirectory = Path.CreateTemporaryDirectory();

File.WriteAllText(Path.Combine(tempDirectory, "file1.txt"), "First file");
File.WriteAllText(Path.Combine(tempDirectory, "file2.txt"), "Second file");

// do something with file1.txt and file2.txt

Directory.Delete(tempDirectory, recursive: true);

Open Questions

  1. Should CreateTemporaryDirectory optionally take a string prefix? mkdtemp allows for prefixes. It would allow for libraries/components to "group" their temp directories together in case users need to find them for some reason.

  2. Should it return DirectoryInfo instead of string? No other methods in Path deal with FileInfo and DirectoryInfo.

  3. We could put it on Directory.CreateTemporaryDirectory() instead of Path - but Path is where GetTempPath and GetTempFileName is. It would be hard to justify putting it in a separate class from the rest of the "temp" methods.

Alternative Designs

Alternatively we could create a full blown TemporaryDirectory class as proposed in #2048. However, that API can be built on top of this one in the future. Adding this lower-level API separately allows for new code to start using it now.

Risks

No response

Metadata

Metadata

Assignees

Labels

api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.IO

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions