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

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

    Hope this self iterating function may help. It works fine for me.

    public string getUniqueFileName(int i, string filepath, string filename)
        {
            string path = Path.Combine(filepath, filename);
            if (System.IO.File.Exists(path))
            {
                string name = Path.GetFileNameWithoutExtension(filename);
                string ext = Path.GetExtension(filename);
                i++;
                filename = getUniqueFileName(i, filepath, name + "_" + i + ext);
            }
            return filename; 
        }
    

提交回复
热议问题