自动重命名文件,如果它已经存在于Windows的方式

我的C#代码是基于input生成几个文本文件并将其保存在一个文件夹中。 此外,我假设文本文件的名称将与input相同(input只包含字母)如果两个文件具有相同的名称,那么它只是覆盖前一个文件。 但是我想保留这两个文件。

我不想将当前date时间或随机数附加到第二个文件名。 相反,我想要像Windows那样做。 如果fisrt文件名是AAA.txt,则第二个文件名是AAA(2).txt,第三个文件名是AAA(3).txt …..第N个文件名将是AAA(N).txt 。

string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); foreach (var item in allFiles) { //newFileName is the txt file which is going to be saved in the provided folder if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase)) { // What to do here ? } } 

这将检查具有tempFileName的文件的存在,并将该数字加1,直到find目录中不存在的名称。

 int count = 1; string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath); string extension = Path.GetExtension(fullPath); string path = Path.GetDirectoryName(fullPath); string newFullPath = fullPath; while(File.Exists(newFullPath)) { string tempFileName = string.Format("{0}({1})", fileNameOnly, count++); newFullPath = Path.Combine(path, tempFileName + extension); } 

如果这个代码的文件名是“Test(3).txt”,那么它将变成“Test(4).txt”。

 public static string GetUniqueFilePath(string filepath) { if (File.Exists(filepath)) { string folder = Path.GetDirectoryName(filepath); string filename = Path.GetFileNameWithoutExtension(filepath); string extension = Path.GetExtension(filepath); int number = 1; Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+"); if (regex.Success) { filename = regex.Groups[1].Value; number = int.Parse(regex.Groups[2].Value); } do { number++; filepath = Path.Combine(folder, string.Format("{0} ({1}){2}", filename, number, extension)); } while (File.Exists(filepath)); } return filepath; } 

其他示例不考虑文件名/扩展名。

干得好:

  public static string GetUniqueFilename(string fullPath) { if (!Path.IsPathRooted(fullPath)) fullPath = Path.GetFullPath(fullPath); if (File.Exists(fullPath)) { String filename = Path.GetFileName(fullPath); String path = fullPath.Substring(0, fullPath.Length - filename.Length); String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath); String ext = Path.GetExtension(fullPath); int n = 1; do { fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext)); } while (File.Exists(fullPath)); } return fullPath; } 

如何只是:

 int count = 1; String tempFileName = newFileName; foreach (var item in allFiles) { if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase)) { tempFileName = String.Format("{0}({1})", newFileName, count++); } } 

这将使用原来的文件名,如果不存在,如果不是,它将采用括号中的索引新的文件名(尽pipe这个代码没有考虑到扩展名)。 如果使用新生成的名称“text(001)”,那么它会增加,直到find一个有效的未使用的文件名。

 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); } 

您可以声明一个Dictionary<string,int>来保存每个根文件名的保存次数。 之后,在你的Save方法中,只需增加计数器并将其附加到基本文件名即可:

 var key = fileName.ToLower(); string newFileName; if(!_dictionary.ContainsKey(key)) { newFileName = fileName; _dictionary.Add(key,0); } else { _dictionary[key]++; newFileName = String.Format("{0}({1})", fileName, _dictionary[key]) } 

这样,您将有一个计数器为每个不同的文件名称:AAA(1),AAA(2); BBB(1)…

现在工作正常。 感谢球员的答案..

 string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray(); string tempFileName = fileName; int count = 1; while (allFiles.Contains(tempFileName )) { tempFileName = String.Format("{0} ({1})", fileName, count++); } output = Path.Combine(folderPath, tempFileName ); string fullPath=output + ".xml"; 
 int count= 0; 

文件是文件的名称

 while (File.Exists(fullpathwithfilename)) //this will check for existence of file { // below line names new file from file.xls to file1.xls fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls"); count++; } 

我正在寻找一个解决scheme,将移动一个文件,并确保如果目标文件名称尚未被采取。 它将遵循与Windows相同的逻辑,并附加一个数字,括号在重复文件之后。

最高的答案,感谢@ cadrell0,帮助我达到了以下解决scheme:

  /// <summary> /// Generates full file path for a file that is to be moved to a destinationFolderDir. /// /// This method takes into account the possiblity of the file already existing, /// and will append number surrounded with brackets to the file name. /// /// Eg if D:\DestinationDir contains file name file.txt, /// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt /// /// </summary> /// <param name="destinationFolderDir">Eg D:\DestinationDir </param> /// <param name="fileToMoveFullPath">D:\Source\file.txt</param> /// <returns></returns> public string GetFullFilePathWithDuplicatesTakenInMind(string destinationFolderDir, string fileToMoveFullPath) { string destinationPathWithDuplicatesTakenInMind; string fileNameWithExtension = Path.GetFileName(fileToMoveFullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath); string fileNameExtension = Path.GetExtension(fileToMoveFullPath); destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension); int count = 0; while (File.Exists(destinationPathWithDuplicatesTakenInMind)) { destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}"); count = count + 1; // sorry, not a fan of the ++ operator. } return destinationPathWithDuplicatesTakenInMind; }