Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a unique temporary file name with a given extension using .NET [duplicate]

Tags:

c#

.net

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?

like image 360
Andrew Shepherd Avatar asked Jul 14 '09 00:07

Andrew Shepherd


People also ask

How do you create a tmp file?

To create and use a temporary fileThe application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.

What is the extension name of temporary file?

Temporary files typically have a . TMP or . TEMP file extension, but any naming convention might be used.

Which operator helps in creating temporary files?

A temp file can be created by directly running mktemp command. The file created can only be read and written by the file owner by default. To ensure the file is created successfully, there should be an OR operator to exit the script if the file fails to be created.


2 Answers

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

like image 89
Mitch Wheat Avatar answered Oct 06 '22 23:10

Mitch Wheat


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.

like image 24
Mircea Grelus Avatar answered Oct 07 '22 01:10

Mircea Grelus