我想创建一个方法,该方法将文件名作为 string
或 FileInfo
并在文件存在时将递增的数字添加到文件名中。但我无法完全理解如何以一种好的方式做到这一点。
例如,如果我有这个 FileInfo
var file = new FileInfo(@"C:\file.ext");
如果 C:\file.ext,我希望该方法给我一个带有 C:\file 1.ext 的新 FileInfo 存在,C:\file 2.ext 如果 C:\file 1.ext 存在等等。像这样:
public FileInfo MakeUnique(FileInfo fileInfo)
{
if(fileInfo == null)
throw new ArgumentNullException("fileInfo");
if(!fileInfo.Exists)
return fileInfo;
// Somehow construct new filename from the one we have, test it,
// then do it again if necessary.
}
最佳答案
public FileInfo MakeUnique(string path)
{
string dir = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string fileExt = Path.GetExtension(path);
for (int i = 1; ;++i) {
if (!File.Exists(path))
return new FileInfo(path);
path = Path.Combine(dir, fileName + " " + i + fileExt);
}
}
显然,这很容易受到其他答案中提到的竞争条件的影响。
关于c# - 您如何通过添加数字来创建唯一的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1078003/