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

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

    Join 4,261 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:

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.

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

  1. Viktor said

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

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.