10

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 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

I KNEW it would be there already. I just couldn't come up with the right search query. Thanks.
This should be a comment, not an answer. If it is a duplicate question, vote to close as such and/or leave a comment once you earn enough reputation. If not, tailor the answer to this specific question.
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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.