How to Generate unique file names in C#

后端 未结 19 2322
生来不讨喜
生来不讨喜 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.

    0 讨论(0)
  • 2020-12-02 06:16

    How about using Guid.NewGuid() to create a GUID and use that as the filename (or part of the filename together with your time stamp if you like).

    0 讨论(0)
  • 2020-12-02 06:17

    If you would like to have the datetime,hours,minutes etc..you can use a static variable. Append the value of this variable to the filename. You can start the counter with 0 and increment when you have created a file. This way the filename will surely be unique since you have seconds also in the file.

    0 讨论(0)
  • 2020-12-02 06:18
    1. Create your timestamped filename following your normal process
    2. Check to see if filename exists
    3. False - save file
    4. True - Append additional character to file, perhaps a counter
    5. Go to step 2
    0 讨论(0)
  • 2020-12-02 06:18

    I have been using the following code and its working fine. I hope this might help you.

    I begin with a unique file name using a timestamp -

    "context_" + DateTime.Now.ToString("yyyyMMddHHmmssffff")

    C# code -

    public static string CreateUniqueFile(string logFilePath, string logFileName, string fileExt)
        {
            try
            {
                int fileNumber = 1;
    
                //prefix with . if not already provided
                fileExt = (!fileExt.StartsWith(".")) ? "." + fileExt : fileExt;
    
                //Generate new name
                while (File.Exists(Path.Combine(logFilePath, logFileName + "-" + fileNumber.ToString() + fileExt)))
                    fileNumber++;
    
                //Create empty file, retry until one is created
                while (!CreateNewLogfile(logFilePath, logFileName + "-" + fileNumber.ToString() + fileExt))
                    fileNumber++;
    
                return logFileName + "-" + fileNumber.ToString() + fileExt;
            }
            catch (Exception)
            {
                throw;
            }
        }
    
        private static bool CreateNewLogfile(string logFilePath, string logFile)
        {
            try
            {
                FileStream fs = new FileStream(Path.Combine(logFilePath, logFile), FileMode.CreateNew);
                fs.Close();
                return true;
            }
            catch (IOException)   //File exists, can not create new
            {
                return false;
            }
            catch (Exception)     //Exception occured
            {
                throw;
            }
        }
    
    0 讨论(0)
  • 2020-12-02 06:21

    I use GetRandomFileName:

    The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name. Unlike GetTempFileName, GetRandomFileName does not create a file. When the security of your file system is paramount, this method should be used instead of GetTempFileName.

    Example:

    public static string GenerateFileName(string extension="")
    {
        return string.Concat(Path.GetRandomFileName().Replace(".", ""),
            (!string.IsNullOrEmpty(extension)) ? (extension.StartsWith(".") ? extension : string.Concat(".", extension)) : "");
    }
    
    0 讨论(0)
提交回复
热议问题