且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多个文件,同名

更新时间:2023-02-23 21:53:35

这太麻烦了。另外,如果 .extension出现在文件名中的其他位置(而不是末尾),则会中断(因此,使您的字符串处理比示例代码更聪明)。如果需要,可以使用 Path.GetExtension(path)

This is off the top of my head. Also, if ".extension" occurs somewhere in the filename other than at the end, this would break (so make your string handling a bit smarter than the sample code). If needed, you can get the extension using Path.GetExtension(path)

if (File.Exists(fn))
{
   int number = 1;
   bool found = false;
   do
   {
       string candidate = fn.Replace(".extension", "[" + number++ + "].extension");
       if (!File.Exists(candidate)) found = true;
   }
   // Candidate has a valid file name
}