.NET/C# – CreateTemporaryRandomDirectory (via: Stack Overflow)
Posted by jpluimers on 2013/06/13
A while ago I needed unique temporary directories. This appears not to be standard functionality in the .NET System.IO.Path or System.IO.Directory class.
Josh Kelley asked a question about it before, and I adapted the example by Scott-Dorman based on GetTempPath and GetRandomFileName and comments by Chris into a more robust CreateTemporaryRandomDirectory one that works in .NET 2.0 and higher:
using System.IO; namespace BeSharp.IO { public class DirectoryHelper { public static string GetTemporaryDirectory() { do { try { string tempPath = Path.GetTempPath(); string randomFileName = Path.GetRandomFileName(); string tempDirectory = Path.Combine(tempPath, randomFileName); Directory.CreateDirectory(tempDirectory); return tempDirectory; } catch (IOException /* ex */) { // continue } } while (true); } } }
You can call it like this:
using System; using BeSharp.IO; namespace CreateTemporaryRandomDirectory { class Program { static void Main(string[] args) { string temporaryDirectory = DirectoryHelper.GetTemporaryDirectory(); Console.WriteLine("Temporary directory {0}", temporaryDirectory); } } }
–jeroen
via: c# – Creating a temporary directory in Windows? – Stack Overflow.
Viktor said
You know, the idea of infinite retries in face of exceptional conditions just makes me shudder :)
jpluimers said
It’s not the most beautiful code I ever wrote (:
If you have an idea for a cleaner way, please let me know!
–jeroen