August 16, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Random File Names using .NET"
  1. Abhishek Sur said...
    August 16, 2010 7:01 AM

    Wow.

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

    :)

    Cool work.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions