-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
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
-
Should CreateTemporaryDirectory optionally take a
string prefix?mkdtempallows for prefixes. It would allow for libraries/components to "group" their temp directories together in case users need to find them for some reason. -
Should it return
DirectoryInfoinstead ofstring? No other methods inPathdeal withFileInfoandDirectoryInfo. -
We could put it on
Directory.CreateTemporaryDirectory()instead ofPath- butPathis whereGetTempPathandGetTempFileNameis. 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