<p>I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem?</p>

[{'answer_id': 16667, 'author': 'jwalkerjr', 'author_id': 689, 'author_profile': 'https://Stackoverflow.com/users/689', 'pm_score': 1, 'selected': False, 'text': "<p>As long as the name of the folder doesn't need to be meaningful, how about using a GUID for them?</p>\n"}, {'answer_id': 16668, 'author': 'Andrew Rimmer', 'author_id': 1982, 'author_profile': 'https://Stackoverflow.com/users/1982', 'pm_score': 2, 'selected': False, 'text': '<p>You could generate a GUID for your temporary folder names.</p>\n'}, {'answer_id': 16671, 'author': 'pix0r', 'author_id': 72, 'author_profile': 'https://Stackoverflow.com/users/72', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <a href="http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx" rel="nofollow noreferrer">GetTempFileName</a> to create a temporary <strong>file</strong>, then delete and re-create this file as a directory instead.</p>\n\n<p>Note: link didn\'t work, copy/paste from: <a href="http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa364991(VS.85).aspx</a></p>\n'}, {'answer_id': 16672, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 4, 'selected': False, 'text': "<p>You have to use <code>System.IO.Path.GetTempFileName()</code></p>\n\n<blockquote>\n  <p>Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.</p>\n</blockquote>\n\n<p>You can use <code>System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName())</code> to get only the temp folder information, and create your folders in there</p>\n\n<p>They are created in the windows temp folder and that's consider a best practice</p>\n"}, {'answer_id': 16685, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 2, 'selected': False, 'text': '<p>Something like...</p>\n\n<pre><code>using System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\nwhile (Directory.Exists(path))\n path = Path.GetTempPath() + Path.GetRandomFileName();\n\nDirectory.CreateDirectory(path);\n</code></pre>\n'}, {'answer_id': 16701, 'author': 'Brian G Swanson', 'author_id': 1795, 'author_profile': 'https://Stackoverflow.com/users/1795', 'pm_score': 1, 'selected': False, 'text': '<p>Combined answers from @adam-wright and pix0r will work the best IMHO:</p>\n\n<pre><code>\nusing System.IO;\n\nstring path = Path.GetTempPath() + Path.GetRandomFileName();\n\nwhile (Directory.Exists(path)) \n  path = Path.GetTempPath() + Path.GetRandomFileName();\n\nFile.Delete(path);\nDirectory.CreateDirectory(path);\n</code></pre>\n'}, {'answer_id': 16707, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 0, 'selected': False, 'text': "<p>The advantage to using System.IO.Path.GetTempFileName is that it will be a file in the user's local (i.e., non-roaming) path. This is exactly where you would want it for permissions and security reasons.</p>\n"}, {'answer_id': 16787, 'author': 'Rick', 'author_id': 1752, 'author_profile': 'https://Stackoverflow.com/users/1752', 'pm_score': 6, 'selected': True, 'text': '<p><strong>Update:</strong> Added File.Exists check per comment (2012-Jun-19)</p>\n\n<p>Here\'s what I\'ve used in VB.NET.   Essentially the same as presented, except I usually didn\'t want to create the folder immediately.  </p>\n\n<p>The advantage to use <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx" rel="noreferrer">GetRandomFilename</a> is that it doesn\'t create a file, so you don\'t have to clean up if your using the name for something other than a file.  Like using it for folder name.</p>\n\n<pre><code>Private Function GetTempFolder() As String\n    Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n    Do While Directory.Exists(folder) or File.Exists(folder)\n        folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n    Loop\n\n    Return folder\nEnd Function\n</code></pre>\n\n<p><strong>Random</strong> Filename Example:</p>\n\n<p>C:\\Documents and Settings\\username\\Local Settings\\Temp\\u3z5e0co.tvq</p>\n\n<hr>\n\n<p>Here\'s a variation using a Guid to get the temp folder name.  </p>\n\n<pre><code>Private Function GetTempFolderGuid() As String\n    Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n    Do While Directory.Exists(folder) or File.Exists(folder)\n        folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)\n    Loop\n\n    Return folder\nEnd Function\n</code></pre>\n\n<p><strong>guid</strong> Example:</p>\n\n<p>C:\\Documents and Settings\\username\\Local Settings\\Temp\\2dbc6db7-2d45-4b75-b27f-0bd492c60496</p>\n'}, {'answer_id': 20710, 'author': 'urini', 'author_id': 373, 'author_profile': 'https://Stackoverflow.com/users/373', 'pm_score': 3, 'selected': False, 'text': '<p>Just to clarify:</p>\n\n<pre><code>System.IO.Path.GetTempPath()\n</code></pre>\n\n<p>returns just the folder path to the temp folder.</p>\n\n<pre><code>System.IO.Path.GetTempFileName()\n</code></pre>\n\n<p>returns the fully qualified file name (including the path) so this:</p>\n\n<pre><code>System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetTempFileName())\n</code></pre>\n\n<p>is redundant.</p>\n'}, {'answer_id': 217198, 'author': 'Jonathan Wright', 'author_id': 28840, 'author_profile': 'https://Stackoverflow.com/users/28840', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s a possible race condition when:</p>\n\n<ul>\n<li>creating a temp file with <code>GetTempFileName()</code>, deleting it, and making a folder with the same name, or</li>\n<li>using <code>GetRandomFileName()</code> or <code>Guid.NewGuid.ToString</code> to name a folder and creating the folder later</li>\n</ul>\n\n<p>With <code>GetTempFileName()</code> after the delete occurs, another application could successfully create a temp file with the same name. The <code>CreateDirectory()</code> would then fail.</p>\n\n<p>Similarly, between calling <code>GetRandomFileName()</code> and creating the directory another process could create a file or directory with the same name, again resulting in <code>CreateDirectory()</code> failing.</p>\n\n<p>For most applications it\'s OK for a temp directory to fail due to a race condition. It\'s extremely rare after all. For them, these races can often be ignored.</p>\n\n<p>In the Unix shell scripting world, creating temp files and directories in a safe race-free way is a big deal. Many machines have multiple (hostile) users -- think shared web host -- and many scripts and applications need to safely create temp files and directories in the shared /tmp directory. See <a href="http://www.linuxsecurity.com/content/view/115462/81/" rel="noreferrer">Safely Creating Temporary Files in Shell Scripts</a> for a discussion on how to safely create temp directories from shell scripts.</p>\n'}, {'answer_id': 8750974, 'author': 'Daniel Trebbien', 'author_id': 196844, 'author_profile': 'https://Stackoverflow.com/users/196844', 'pm_score': 3, 'selected': False, 'text': '<p>As @JonathanWright <a href="https://stackoverflow.com/a/217198/196844">pointed out</a>, race conditions exist for the solutions:</p>\n\n<ul>\n<li>Create a temporary file with <code>GetTempFileName()</code>, delete it, and create a folder with the same name</li>\n<li>Use <code>GetRandomFileName()</code> or <code>Guid.NewGuid.ToString</code> to create a random folder name, check whether it exists, and create it if not.</li>\n</ul>\n\n<p>It is possible, however, to create a unique temporary directory atomically by utilizing the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363764.aspx" rel="nofollow noreferrer">Transactional NTFS</a> (TxF) API.</p>\n\n<p>TxF has a <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363857.aspx" rel="nofollow noreferrer"><code>CreateDirectoryTransacted()</code></a> function that can be invoked via Platform Invoke. To do this, I adapted <a href="http://www.codeproject.com/Articles/66276/Creating-Transacted-Files-in-Windows-Vista.aspx?display=Print" rel="nofollow noreferrer">Mohammad Elsheimy\'s code</a> for calling <code>CreateFileTransacted()</code>:</p>\n\n<pre><code>// using System.ComponentModel;\n// using System.Runtime.InteropServices;\n// using System.Transactions;\n\n[ComImport]\n[Guid("79427a2b-f895-40e0-be79-b57dc82ed231")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IKernelTransaction\n{\n    void GetHandle(out IntPtr pHandle);\n}\n\n// 2.2 Win32 Error Codes &lt;http://msdn.microsoft.com/en-us/library/cc231199.aspx&gt;\npublic const int ERROR_PATH_NOT_FOUND = 0x3;\npublic const int ERROR_ALREADY_EXISTS = 0xb7;\npublic const int ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION = 0x1aaf;\n\n[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]\npublic static extern bool CreateDirectoryTransacted(string lpTemplateDirectory, string lpNewDirectory, IntPtr lpSecurityAttributes, IntPtr hTransaction);\n\n/// &lt;summary&gt;\n/// Creates a uniquely-named directory in the directory named by &lt;paramref name="tempPath"/&gt; and returns the path to it.\n/// &lt;/summary&gt;\n/// &lt;param name="tempPath"&gt;Path of a directory in which the temporary directory will be created.&lt;/param&gt;\n/// &lt;returns&gt;The path of the newly-created temporary directory within &lt;paramref name="tempPath"/&gt;.&lt;/returns&gt;\npublic static string GetTempDirectoryName(string tempPath)\n{\n    string retPath;\n\n    using (TransactionScope transactionScope = new TransactionScope())\n    {\n        IKernelTransaction kernelTransaction = (IKernelTransaction)TransactionInterop.GetDtcTransaction(Transaction.Current);\n        IntPtr hTransaction;\n        kernelTransaction.GetHandle(out hTransaction);\n\n        while (!CreateDirectoryTransacted(null, retPath = Path.Combine(tempPath, Path.GetRandomFileName()), IntPtr.Zero, hTransaction))\n        {\n            int lastWin32Error = Marshal.GetLastWin32Error();\n            switch (lastWin32Error)\n            {\n                case ERROR_ALREADY_EXISTS:\n                    break;\n                default:\n                    throw new Win32Exception(lastWin32Error);\n            }\n        }\n\n        transactionScope.Complete();\n    }\n    return retPath;\n}\n\n/// &lt;summary&gt;\n/// Equivalent to &lt;c&gt;GetTempDirectoryName(Path.GetTempPath())&lt;/c&gt;.\n/// &lt;/summary&gt;\n/// &lt;seealso cref="GetTempDirectoryName(string)"/&gt;\npublic static string GetTempDirectoryName()\n{\n    return GetTempDirectoryName(Path.GetTempPath());\n}\n</code></pre>\n'}, {'answer_id': 18579763, 'author': 'jri', 'author_id': 1655724, 'author_profile': 'https://Stackoverflow.com/users/1655724', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Dim NewFolder = System.IO.Directory.CreateDirectory(IO.Path.Combine(IO.Path.GetTempPath, Guid.NewGuid.ToString))\n</code></pre>\n'}, {'answer_id': 39467623, 'author': 'Wilco BT', 'author_id': 4153333, 'author_profile': 'https://Stackoverflow.com/users/4153333', 'pm_score': 0, 'selected': False, 'text': '<p>@JonathanWright suggests CreateDirectory will fail when there is already a folder. If I read Directory.CreateDirectory it says \'This object is returned regardless of whether a directory at the specified path already exists.\' Meaning you do not detect a folder created between check exists and actually creating.</p>\n\n<p>I like the CreateDirectoryTransacted() suggested by @DanielTrebbien but this function is deprecated.</p>\n\n<p>The only solution I see that is left is to use the c api and call the \'<a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx" rel="nofollow">CreateDirectory</a>\' there as it does error if the folder exists if you really need to be sure to cover the whole race condition.\nThat would result in something like this:</p>\n\n<pre><code>Private Function GetTempFolder() As String\n    Dim folder As String\n    Dim succes as Boolean = false\n    Do While not succes\n        folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)\n        success = c_api_create_directory(folder)\n    Loop\n    Return folder\nEnd Function\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/16656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1632/']