Saturday, February 12, 2011

Try to generate unique file names in C#

Few days ago i face an issue with file names when trying to upload multiple files at a time and then save them to hard drive because if i select multiple files with same name in two different browse control it will save first one only as two files with same name are not allowed to create. After some research i found out the solution which many people likes, So i decided to share it with everyone.

Solution:
First of all readability of file names are not important to me, So i make a string by concatenating GUID with another string comprises of DayMonthYearHourMinuteSecondMilliSecond

How to generate this
string uniqueString = Guid.NewGuid() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); 

and the final string look likes this

ccff9944-2af8-4318-bd94-15b8448da25d1222011122211660

To validate if this logic is achieving my goal i put this in a loop and set its counter to 500 and every string which i get is unique.

What is GUID
GUID is Globally Unique Identifier which is a 32 character hexadecimal string and is usually stored as a 128 bit integer. Example of GUID is 936DA01F-9ABD-4d9d-80C7-02AF85C822A8
For reference you can read this article on msdn about GUID Structure.

No comments:

Post a Comment