9

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?

Community
  • 1
  • 1
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205

2 Answers2

11

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

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • I KNEW it would be there already. I just couldn't come up with the right search query. Thanks. – Andrew Shepherd Jul 14 '09 at 00:57
  • This should be a comment, not an answer. If it is a duplicate question, [vote to close](/help/privileges/close-questions) as such and/or leave a comment once you [earn](//meta.stackoverflow.com/q/146472) enough [reputation](/help/whats-reputation). If not, *tailor the answer to this specific question*. – Jim G. Jul 28 '22 at 17:08
1

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
  • 2,905
  • 1
  • 20
  • 14
  • GUIDs do sometimes clash when created from the same process on the same machine at around the same time. That racecondition is probably no safer than the GetTempFileName() in the first place. – Robert Jørgensgaard Engdahl Sep 18 '18 at 09:16