How to Generate unique file names in C#

后端 未结 19 2321
生来不讨喜
生来不讨喜 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:33

    If the readability of the file name isn't important, then the GUID, as suggested by many will do. However, I find that looking into a directory with 1000 GUID file names is very daunting to sort through. So I usually use a combination of a static string which gives the file name some context information, a timestamp, and GUID.

    For example:

    public string GenerateFileName(string context)
    {
        return context + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N");
    }
    
    filename1 = GenerateFileName("MeasurementData");
    filename2 = GenerateFileName("Image");
    

    This way, when I sort by filename, it will automatically group the files by the context string and sort by timestamp.

    Note that the filename limit in windows is 255 characters.

    0 讨论(0)
提交回复
热议问题