C#: How would you make a unique filename by adding a number?

前端 未结 18 779
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 11:46

I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file

18条回答
  •  一生所求
    2020-11-27 11:57

    Not pretty, but I've had this for a while :

    private string getNextFileName(string fileName)
    {
        string extension = Path.GetExtension(fileName);
    
        int i = 0;
        while (File.Exists(fileName))
        {
            if (i == 0)
                fileName = fileName.Replace(extension, "(" + ++i + ")" + extension);
            else
                fileName = fileName.Replace("(" + i + ")" + extension, "(" + ++i + ")" + extension);
        }
    
        return fileName;
    }
    

    Assuming the files already exist:

    • File.txt
    • File(1).txt
    • File(2).txt

    the call getNextFileName("File.txt") will return "File(3).txt".

    Not the most efficient because it doesn't use binary search, but should be ok for small file count. And it doesn't take race condition into account...

提交回复
热议问题