Why is TempFileCollection throwing an exception in AddExtension ("tmp")?
Does anyone know why the code below is throwing a System.ArgumentException?
using (var tfc = new TempFileCollection())
{
var fn = tfc.AddExtension("tmp");
Console.WriteLine(fn);
}
Here's the exact exception:
System.ArgumentException: The file name 'C:\Users\pczapla\AppData\Local\Temp\iqulrqva.tmp' was already in the collection.
Parameter name: fileName.
source to share
Small Action Reflector shows 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);
It is in TempFileCollection.EnsureTempNameCreated
which is called TempFileCollection.BasePath
, which is called TempFileCollection.AddExtension
. I assume the placeholder uses ".tmp", which is why you can't.
source to share
It seems that the first time the method is called, AddExtension
it will automatically add the filename with the extension "tmp" to the collection, and then try to add the filename with the specified extension.
So if you give "tmp" as the extension, then it will try to add the same file twice, throwing an 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. Note that it includes a filename with a "tmp" extension, which we do not 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
source to share