Skip to content

Getting a temporary filename the easy way - feedback

Thu May 04 2006

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:
csharp
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.

💾 May the source be with you. v3.2.419