Creating a temporary directory in Windows?

What is the best way to get the temporary directory name on Windows? I see that I can use GetTempPath and GetTempFileName to create a temporary file, but is there any Linux / BSD mkdtemp to create a temporary directory?

+79
c # windows temporary-directory
Nov 10 '08 at 16:50
source share
8 answers

No, there is no equivalent to mkdtemp. A better option is to use a combination of GetTempPath and GetRandomFileName .

You will need code similar to this:

 public string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } 
+156
Nov 10 '08 at 16:55
source share

I will hack Path.GetTempFileName() to give me a valid pseudo-random path to a file on disk, then delete the file and create a directory with the same path.

This avoids the need to check if the path to the file is available in a time or a cycle, to Chrisโ€™s comment regarding Scott Dormanโ€™s response.

 public string GetTemporaryDirectory() { string tempFolder = Path.GetTempFileName(); File.Delete(tempFolder); Directory.CreateDirectory(tempFolder); return tempFolder; } 

If you really need a cryptographically secure random name, you may need to adapt Scott's answer to take some time or to do a loop to try to create a drive path.

+14
Dec 07 '13 at 20:01
source share

I like to use GetTempPath (), a GUID creation function like CoCreateGuid () and CreateDirectory ().

A GUID is designed for a high probability of uniqueness, and it is also very unlikely that someone manually created a directory with the same form as the GUID (and if they do, CreateDirectory () will not be able to indicate its existence).

+7
Aug 06 '10 at 4:59
source share

GetTempPath is the right way to do this; I'm not sure if you are worried about this method. You can use CreateDirectory to do this.

+1
Nov 10 '08 at 16:55
source share

Here's a slightly grosser approach to solving the collision problem for temporary directory names. This is not an error-free approach, but it significantly reduces the likelihood of a collision with the path of the folder.

Other information related to the process or assembly could be added to the directory name to make the collision even less likely, although such information visible in the temporary directory may not be desirable. You can also mix the order in which time-related fields are combined to make folder names more random. I personally prefer to leave it so simple, because I find it easier to find them during debugging.

 string randomlyGeneratedFolderNamePart = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); string timeRelatedFolderNamePart = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); string processRelatedFolderNamePart = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); string temporaryDirectoryName = Path.Combine( Path.GetTempPath() , timeRelatedFolderNamePart + processRelatedFolderNamePart + randomlyGeneratedFolderNamePart); 
+1
Dec 09 '13 at 23:48
source share

@Chris. I, too, was obsessed with the remote risk that a temporary directory might already exist. Discussions about random and cryptographically strong do not completely satisfy me.

My approach is based on the fundamental fact that O / S does not allow two calls to create a file for both. It's a little surprising that the .NET developers decided to hide the functionality of the Win32 API for directories, which makes it much easier since it returns an error when trying to create a directory for the second time. Here is what I use:

  [DllImport(@"kernel32.dll", EntryPoint = "CreateDirectory", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CreateDirectoryApi ([MarshalAs(UnmanagedType.LPTStr)] string lpPathName, IntPtr lpSecurityAttributes); /// <summary> /// Creates the directory if it does not exist. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <returns>Returns false if directory already exists. Exceptions for any other errors</returns> /// <exception cref="System.ComponentModel.Win32Exception"></exception> internal static bool CreateDirectoryIfItDoesNotExist([NotNull] string directoryPath) { if (directoryPath == null) throw new ArgumentNullException("directoryPath"); // First ensure parent exists, since the WIN Api does not CreateParentFolder(directoryPath); if (!CreateDirectoryApi(directoryPath, lpSecurityAttributes: IntPtr.Zero)) { Win32Exception lastException = new Win32Exception(); const int ERROR_ALREADY_EXISTS = 183; if (lastException.NativeErrorCode == ERROR_ALREADY_EXISTS) return false; throw new System.IO.IOException( "An exception occurred while creating directory'" + directoryPath + "'".NewLine() + lastException); } return true; } 

You can decide if the "cost / risk" of the unmanaged p / invoke code is worth it. Most would say that this is not so, but at least you now have a choice.

CreateParentFolder () remains as an exercise for the student. I am using Directory.CreateDirectory (). Be careful when getting the parent directory as it is null when it is in the root.

+1
Jan 10 '16 at 10:42 on
source share

As mentioned above, Path.GetTempPath () is one way to do this. You can also call Environment.GetEnvironmentVariable ("TEMP") if the user has the TEMP environment variable set.

If you plan to use a temporary directory as a means of storing data in the application, you should probably look at IsolatedStorage as a repository for configuration / state / etc ...

0
Nov 10 '08 at 17:05
source share

I usually use this:

  /// <summary> /// Creates the unique temporary directory. /// </summary> /// <returns> /// Directory path. /// </returns> public string CreateUniqueTempDirectory() { var uniqueTempDir = Path.GetFullPath(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); Directory.CreateDirectory(uniqueTempDir); return uniqueTempDir; } 

If you want to be absolutely sure that this directory name will not exist in the temp path, you need to check if this unique directory name exists and try to create another one if it really exists.

But this GUID-based implementation is enough. In this case, I have no problem with any problem. Some MS applications also use temporary directories based on GUIDs.

0
Sep 02 '16 at 7:25
source share



All Articles