C# 为什么TempFileCollection在AddExtension(“tmp”)上抛出异常?

C# 为什么TempFileCollection在AddExtension(“tmp”)上抛出异常?,c#,.net,C#,.net,有人知道下面的代码为什么抛出System.ArgumentException吗 using (var tfc = new TempFileCollection()) { var fn = tfc.AddExtension("tmp"); Console.WriteLine(fn); } 这里有一个确切的例外: System.ArgumentException: The file name 'C:\Users\pczapla\AppData\Loc

有人知道下面的代码为什么抛出System.ArgumentException吗

using (var tfc = new TempFileCollection())
{                
    var fn = tfc.AddExtension("tmp");
    Console.WriteLine(fn);
}
这里有一个确切的例外:

System.ArgumentException: The file name 'C:\Users\pczapla\AppData\Local\Temp\iqulrqva.tmp' was already in the collection.
Parameter name: fileName.

似乎在您第一次调用
AddExtension
方法时,它会自动将扩展名为“tmp”的文件名添加到集合中,然后再尝试添加扩展名为指定扩展名的文件名

因此,如果您指定“tmp”作为扩展名,那么它将尝试添加相同的文件两次,从而导致异常

using (var tfc = new TempFileCollection())
{
    var foo = tfc.AddExtension("foo");
    var bar = tfc.AddExtension("bar");

    foreach (var f in tfc)
    {
        Console.WriteLine(f);
    }
}
上面的代码将生成以下输出。请注意,它包含一个扩展名为“tmp”的文件名,我们没有明确添加它

C:\Users\Luke\AppData\Local\Temp\jmat4jqg.tmp
C:\Users\Luke\AppData\Local\Temp\jmat4jqg.bar
C:\Users\Luke\AppData\Local\Temp\jmat4jqg.foo

TempFileCollection
中,一个小小的反射器动作揭示了以下有趣的片段:

new FileIOPermission(FileIOPermissionAccess.AllAccess, basePath).Demand();
path = this.basePath + ".tmp";
using (new FileStream(path, FileMode.CreateNew, FileAccess.Write))
{
}
flag = true;
...
this.files.Add(path, this.keepFiles);
这在
TempFileCollection.EnsureTempNameCreated
中,由
TempFileCollection.BasePath
调用,由
TempFileCollection.AddExtension
调用。我猜占位符使用了“.tmp”,所以您不能