How to Generate unique file names in C#

后端 未结 19 2318
生来不讨喜
生来不讨喜 2020-12-02 05:43

I have implemented an algorithm that will generate unique names for files that will save on hard drive. I\'m appending DateTime: Hours,Minutes,Second an

19条回答
  •  有刺的猬
    2020-12-02 06:16

    Why can't we make a unique id as below.

    We can use DateTime.Now.Ticks and Guid.NewGuid().ToString() to combine together and make a unique id.

    As the DateTime.Now.Ticks is added, we can find out the Date and Time in seconds at which the unique id is created.

    Please see the code.

    var ticks = DateTime.Now.Ticks;
    var guid = Guid.NewGuid().ToString();
    var uniqueSessionId = ticks.ToString() +'-'+ guid; //guid created by combining ticks and guid
    
    var datetime = new DateTime(ticks);//for checking purpose
    var datetimenow = DateTime.Now;    //both these date times are different.
    

    We can even take the part of ticks in unique id and check for the date and time later for future reference.

    You can attach the unique id created to the filename or can be used for creating unique session id for login-logout of users to our application or website.

提交回复
热议问题