tags:

views:

62

answers:

2

Does anyone know why the code below throws System.ArgumentException?

using (var tfc = new TempFileCollection())
{                
    var fn = tfc.AddExtension("tmp");
    Console.WriteLine(fn);
}

Here is exact exception:

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

It seems that the first time you call the AddExtension method, it will automatically add a filename with the "tmp" extension to the collection before then trying to add the filename with your specified extension.

So if you specify "tmp" as the extension then it will try to add the same file twice, causing the exception.

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

    foreach (var f in tfc)
    {
        Console.WriteLine(f);
    }
}

The above code will generate the following output. Notice that it includes a filename with the "tmp" extension that we didn't explicitly add.

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

A little Reflector action reveals the following interesting snippet in 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);

This is in TempFileCollection.EnsureTempNameCreated, which is called by TempFileCollection.BasePath, which is called by TempFileCollection.AddExtension. I guess the placeholder uses ".tmp" so you cannot.

sixlettervariables