The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

.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:

[sourcecode language=”csharp”]
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);
}
}
}
[/sourcecode]

You can call it like this:

[sourcecode language=”csharp”]
using System;
using BeSharp.IO;

namespace CreateTemporaryRandomDirectory
{
class Program
{
static void Main(string[] args)
{
string temporaryDirectory = DirectoryHelper.GetTemporaryDirectory();
Console.WriteLine("Temporary directory {0}", temporaryDirectory);
}
}
}
[/sourcecode]

–jeroen

via: c# – Creating a temporary directory in Windows? – Stack Overflow.

2 Responses to “.NET/C# – CreateTemporaryRandomDirectory (via: Stack Overflow)”

  1. Viktor's avatar

    Viktor said

    You know, the idea of infinite retries in face of exceptional conditions just makes me shudder :)

    • jpluimers's avatar

      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

Leave a Comment

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading