Home
C#
Path.GetRandomFileName Method
Updated Jan 3, 2025
Dot Net Perls
Path.GetRandomFileName. This C# method from System.IO generates random file names. We can use these to store data in a secret (or unique) way.
Random filename benefits. The filename does not conflict with other files. It will not be corrupted by other programs. We can write the file and expect it to be left alone.
Path
First, there are many ways to generate random strings. You could develop a method that populates a char array using the Random class, and then returns a string based on those numbers.
Random
However We can access the Path.GetRandomFileName static method, which returns appropriate strings.
static
Detail This method gets a random file name, gets the correct output path on the C:\ volume, and then writes some text to it.
Return The Path.GetRandomFileName method returns a random file name with an extension. This includes the period before the extension.
return
Tip The extension will be 1 dot and 3 letters, while the name will be 8 characters. All the characters are valid file name characters.
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"); } }
m4adstid.dw2 mbhbtcen.5m1 1qtk3r5u.bka
Implementation. Internally, the Path.GetRandomFileName method gets random bytes from the cryptographic-quality random number generator RNGCryptoServiceProvider.
Next The method uses bitwise ANDs to fill a StringBuilder with characters based on those bytes.
RNGCryptoServiceProvider
StringBuilder
Summary. We generated random file names to store certain kinds of data. By using Path.GetRandomFileName, you can write to files that have secure random names.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 3, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen