c# - 您如何通过添加数字来创建唯一的文件名?

标签 c# unique filenames

我想创建一个方法,该方法将文件名作为 stringFileInfo 并在文件存在时将递增的数字添加到文件名中。但我无法完全理解如何以一种好的方式做到这一点。

例如,如果我有这个 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/

相关文章:

windows - 对名为 guid 的目录进行排序

c# - 反射调用方法 - 参数异常

c# - Angular 6 中的 cors 策略已阻止从源访问 xmlhttprequest

c# - 使用 LINQ 获取所有可能的不同三元组

python - 如何获取二维数组的唯一行及其出现次数?

python - 如何在 Python 中替换(或去除)文件名的扩展名?

c# - 比较 .NET 中的两个字节数组

c# - 当角色可以组合到其他角色时,如何从列表中获取所有角色组合

c++ - 查找 std::vector 中每个唯一值的频率的有效方法

http - 无法找到在 weblogic 下运行 servlet 的 HTTP PUT 请求的原始文件名