TheDeveloperBlog.com


C# Path.GetRandomFileName Method

Path.GetRandomFileName generates random file names. We can use these to store data in a secret (or unique) way. The filename does not conflict with other files. It will not be corrupted by other programs.


Example. First, there are many different ways of generating random strings and file names in the C# language. You could develop a method that populates a char array using the Random class, and then returns a string based on those numbers.

However: The .NET Framework offers the excellent Path.GetRandomFileName static parameterless method, which returns appropriate strings.

C# program that writes random file names

using System;
using System.IO;

class Program
{
    static void Main()
    {
	//
	// Write three random files.
	//
	WriteRandomFile();
	WriteRandomFile();
	WriteRandomFile();
    }

    static void WriteRandomFile()
    {
	//
	// Get random file name.
	//
	string fileName = Path.GetRandomFileName();
	//
	// Construct full path.
	//
	string outputPath = Path.Combine("C:\\", fileName);
	//
	// Write to screen and disk.
	//
	Console.WriteLine(fileName);
	File.WriteAllText(outputPath, "Random");
    }
}

Output

m4adstid.dw2
mbhbtcen.5m1
1qtk3r5u.bka

We see the WriteRandomFile is called three times. The WriteRandomFile method internally gets a random file name, gets the correct output path on the C:\ volume, and then writes some text to it.

The Path.GetRandomFileName method returns a random file name with an extension. This includes the period before the extension. The extension will be 1 dot and 3 letters, while the name will be 8 characters.

And: All the characters are valid file name characters. So we can reliably create a new file with the name.


Internals. Internally, the Path.GetRandomFileName method gets random bytes from the cyptographic-quality random number generator RNGCryptoServiceProvider. Next, it uses bitwise ANDs to fill a StringBuilder with characters based on those bytes.

RNGCryptoServiceProvider

The ToBase32String method uses a StringBuilder to generate the file name. When that method returns, the StringBuilder is converted to a string. In the calling method, the string is converted to a char array.

Finally: The char array is converted to a string. This method could probably be significantly optimized.


Summary. We generated random file names to store certain kinds of data. By using Path.GetRandomFileName, you can write to files that have cryptographically-secure random names. This can enhance security or simplicity in your programs.