Automatically rename a file if it already exists in Windows way

前端 未结 10 637
谎友^
谎友^ 2020-11-28 06:50

My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input.(The input

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 07:08

    public static string AutoRenameFilename(FileInfo file)
        {
            var filename = file.Name.Replace(file.Extension, string.Empty);
            var dir = file.Directory.FullName;
            var ext = file.Extension;
    
            if (file.Exists)
            {
                int count = 0;
                string added;
    
                do
                {
                    count++;
                    added = "(" + count + ")";
                } while (File.Exists(dir + "\\" + filename + " " + added + ext));
    
                filename += " " + added;
            }
    
            return (dir + filename + ext);
        }
    

提交回复
热议问题