Search code examples
c#.netwindowstemporary-directory

Creating a temporary directory in Windows?


What's the best way to get a temp directory name in Windows? I see that I can use GetTempPath and GetTempFileName to create a temporary file, but is there any equivalent to the Linux / BSD mkdtemp function for creating a temporary directory?


Solution

  • No, there is no equivalent to mkdtemp. The best option is to use a combination of GetTempPath and GetRandomFileName.

    You would need code similar to this:

    public string GetTemporaryDirectory()
    {
        string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
    
        if(File.Exist(tempDirectory)) {
            return GetTemporaryDirectory();
        } else {
            Directory.CreateDirectory(tempDirectory);
            return tempDirectory;
        }
    }