How to Generate unique file names in C#

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

    I've written a simple recursive function that generates file names like Windows does, by appending a sequence number prior to the file extension.

    Given a desired file path of C:\MyDir\MyFile.txt, and the file already exists, it returns a final file path of C:\MyDir\MyFile_1.txt.

    It is called like this:

    var desiredPath = @"C:\MyDir\MyFile.txt";
    var finalPath = UniqueFileName(desiredPath);
    
    private static string UniqueFileName(string path, int count = 0)
    {
        if (count == 0)
        {
            if (!File.Exists(path))
            {
                return path;
            }
        }
        else
        {
            var candidatePath = string.Format(
                @"{0}\{1}_{2}{3}",
                Path.GetDirectoryName(path),
                Path.GetFileNameWithoutExtension(path),
                count,
                Path.GetExtension(path));
    
            if (!File.Exists(candidatePath))
            {
                return candidatePath;
            }
        }
    
        count++;
        return UniqueFileName(path, count);
    }
    

提交回复
热议问题