tags:

views:

521

answers:

2

Possible Duplicate:
How can I create a temp file with a specific extension with .net ?

It is possible to create a temporary file in .NET by calling

string fileName = System.IO.Path.GetTempFileName();

This will create a file with a .TMP extension in the temporary directory.

What if you specifically want it to have a different extension? For the sake of this example, lets say that I needed a file ending with .TR5.

The obvious (and buggy) solution is to call

string fileName = Path.ChangeExtension(Path.GetTempFileName(), "tr5"))

The problems here are:

  • It has still generated an empty file (eg tmp93.tmp) in the temp directory, which will now hang around indefinitely
  • There is no gurantee that the resulting filename (tmp93.tr5) isn't already existing

Is there a straightforward and safe way to generate a temporary file with a specific file exension?

+2  A: 

Please See: How can I create a temp file with a specific extension with .net ?

Mitch Wheat
I KNEW it would be there already. I just couldn't come up with the right search query. Thanks.
Andrew Shepherd
A: 

I don't know if there's a supported method for generating an extension other than .tmp, but this will give you a unique file:

string fileName = Path.ChangeExtension(Path.GetTempFileName(), Guid.NewGuid().ToString() + "tr5"))

Not an elegant solution and I'm not sure if you need to then retrieve based on specific extension, but you could still write a pattern even for this.

Mircea Grelus
this answer essentially duplicates the one linked to :)
Mitch Wheat
I've noticed that after I posted it.
Mircea Grelus