How to Generate unique file names in C#

后端 未结 19 2504
生来不讨喜
生来不讨喜 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: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;
            }
        }
    

提交回复
热议问题