Automatically rename a file if it already exists in Windows way

前端 未结 10 635
谎友^
谎友^ 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:19

    With this code if file name is "Test (3).txt" then it will become "Test (4).txt".

    public static string GetUniqueFilePath(string filePath)
    {
        if (File.Exists(filePath))
        {
            string folderPath = Path.GetDirectoryName(filePath);
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            string fileExtension = Path.GetExtension(filePath);
            int number = 1;
    
            Match regex = Regex.Match(fileName, @"^(.+) \((\d+)\)$");
    
            if (regex.Success)
            {
                fileName = regex.Groups[1].Value;
                number = int.Parse(regex.Groups[2].Value);
            }
    
            do
            {
                number++;
                string newFileName = $"{fileName} ({number}){fileExtension}";
                filePath = Path.Combine(folderPath, newFileName);
            }
            while (File.Exists(filePath));
        }
    
        return filePath;
    }
    

提交回复
热议问题