Random File Names using .NET

It helps to have knowledge of .NET classes. I was recently working on a requirement where some files were to be generated on the fly and stored on the disk. The requirement was that the files had to be generated with random characters and random extensions, to add extra security to the files. System.IO.Path.GetRandomFileName() returns a random folder name or file name which makes the task very simple, as shown below:

C#

static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
Console.WriteLine(System.IO.Path.GetRandomFileName());
Console.ReadLine();
}

VB.NET

Shared Sub Main(ByVal args() As String)
For i As Integer = 1 To 9
Console.WriteLine(System.IO.Path.GetRandomFileName())
Next i
Console.ReadLine()
End Sub

Note: If you want to physically create some files on the disk, just pass these random names to a FileStream object inside the for loop. GetRandomFileName() does not create a physical file like GetTempFileName() does.

OUTPUT

image

1 comment:

  1. Wow.

    Very easy to generate random filenames. The problem will occur when the filename coincides.

    :)

    Cool work.

    ReplyDelete