Thursday, May 04, 2006 3:02 PM Christopher

Getting a temporary filename the easy way

If you need to generate temporary / semi-unique filenames, here is a little snippet that uses the framework:

using System.IO;

string GetTempFileName(){
	return Path.GetFileNameWithoutExtension(Path.GetTempFileName());
}

As the name implies, this will return the temporary name of a file without the extension, so it's up to you to add whatever filetype you may be trying to create. For example, let's say I wanted to generate a .gif:

string GetTempGifFileName(){
	return string.Format("{0}.{1}", GetTempFileName(), "gif");
}

I had overlooked this little piece of functionality because the component that I was using generated filenames with GUIDs, so I never really worried about it. Way to make my life easier, .netfx :)

[ Currently Playing : Mississippi Queen - Ozzy Osbourne - Under Cover (4:11) ]

Filed under:

Comments

# re: Getting a temporary filename the easy way

Thursday, May 04, 2006 4:07 PM by Jerry Pisk

Path.GetTempFileName() guarantees that you will get an available name, it does actually go ahead and create the file so it is guaranteed to be yours when you use it. If you strip the extension off and substitute your own you may end up overwriting an existing file. Not a smart thing to do.

# re: Getting a temporary filename the easy way

Thursday, May 04, 2006 4:41 PM by Paul Welter

Be aware the GetTempFileName() actually creates a zero byte file in the temp folder. Your code will leave the temp file behind in the temp folder. If you use that a lot, you will end up with a lot of files in the temp folder.

# re: Getting a temporary filename the easy way

Friday, May 05, 2006 12:51 PM by Jb Evain

string.Format("{0}.{1}", ...);

Wow,
This is such a waste of resource only to concatenate three strings.

# re: Getting a temporary filename the easy way

Friday, May 05, 2006 1:16 PM by Chris Frazier

How is it such a waste of resource? Enlighten me.

# re: Getting a temporary filename the easy way

Monday, May 08, 2006 8:45 AM by Jb Evain

Oops,

Sorry for the long time before answering.
Consider the following code:

using System;
using System.Text;

class Test {

static void Format ()
{
string.Format ("{0}.{1}", "foo", "bar");
}

static void Concat ()
{
string.Concat ("foo", ".", "bar");
}

static void Main ()
{
int run = 100000;

DateTime start = DateTime.Now;
for (int i = 0; i < run; i++)
Format ();
Console.WriteLine ("Format: {0}", (DateTime.Now - start));

start = DateTime.Now;
for (int i = 0; i < run; i++)
Concat ();
Console.WriteLine ("Concat: {0}", (DateTime.Now - start));
}
}

Run it and you'll see that the format takes much more time to do its task (mostly due to parsing).

Jb

# re: Getting a temporary filename the easy way

Monday, May 08, 2006 12:35 PM by Chris Frazier

:) thanks for enlightening me.

Leave a Comment

(required) 
(required) 
(optional)
(required)