Unique ID Creation in C#

We face so many times the same issue as we need to create a random unique ID. Here is the sample code

   
                int idgenerated = 0;
                foreach (var item in items)
                {
                    try
                    {
                        int index = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
                        index = Math.Abs((int)index);
                        idgenerated = index;
                        idgenerated++;
                    }
                    catch (Exception Ex)
                    {
                        Console.WriteLine(Ex);
                    }
                }
                Console.WriteLine(idgenerated);
 //OR
 long ticks = DateTime.Now.Ticks;
 byte[] bytes = BitConverter.GetBytes(ticks);
 string id = Convert.ToBase64String(bytes)
                         .Replace('+', '_')
                         .Replace('/', '-')
                         .TrimEnd('=');
 Console.WriteLine (id);

 

Read more...