May 2006 - Posts

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.

In my case, I just really want the filename. Whether or not I change the extension, that file is mine to do with what I will. Also, since it's not in the same folder as the originating file, it can be the exact same name, extension and all, and it will still be a different file that what was generated by the framework. I should take care of file cleanup, and that zero byte file is still in the temp directory...

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.

true! So, maybe I was a little quick to post about this one, but it was one of those things that struck me as particularly useful. If you just want a temporary filename, and want to clean up the file that is created by GetTempFileName(), perhaps this will work a little better:

string GetTempFileName(){
	string filename = Path.GetTempFileName();

	File.Delete(filename);

	return Path.GetFileNameWithoutExtension(filename);
}

Okay y'all...rip it to shreds :) If I've missed something else obvious, call me out. Or, if you have a preferred method of generating temporary file names, show the 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) ]

More Posts