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

前端 未结 18 817
没有蜡笔的小新
没有蜡笔的小新 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 12:13

    public FileInfo MakeUnique(string path)
    {            
        string dir = Path.GetDirectoryName(path);
        string fileName = Path.GetFileNameWithoutExtension(path);
        string fileExt = Path.GetExtension(path);
    
        for (int i = 1; ;++i) {
            if (!File.Exists(path))
                return new FileInfo(path);
    
            path = Path.Combine(dir, fileName + " " + i + fileExt);
        }
    }
    

    Obviously, this is vulnerable to race conditions as noted in other answers.

提交回复
热议问题