新建一个文件,保存时对文件名进行检查,若重名则按照Windows系统中的方法,加数字与括号进行处理。
using System.IO;
public static string getUniqueFileName(string filePath)
{
string directory = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int counter = 1;
string newFileName = fileName;
while (File.Exists(Path.Combine(directory, newFileName + fileExtension)))
{
newFileName = $"{fileName} ({counter})";
counter++;
}
string newFilePath = Path.Combine(directory, newFileName + fileExtension);
return newFilePath;
}