Saturday, December 29, 2007

C#: Generate a temporary file name on disk

public string GetTemporaryFile(string extn)
{
string response = string.Empty;

if (!extn.StartsWith("."))
extn = "." + extn;

response = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + extn;

return response;
}

13 comments:

  1. very useful thanks
    N

    ReplyDelete
  2. No need to invent what's been provided by the runtime. Take a look at:

    Path.GetTempFileName()

    Mike

    ReplyDelete
  3. Mike, You would notice that I AM currently using some of the .Net stuff already (System.IO.Path.GetTempPath()), however I had to write the code above since a simple Path.GetTempFileName() does not assign an extension by default. Makes sense?

    ReplyDelete
  4. This code does not guarantee that you have unique filename. This will work for 99% of regular buggy applications, but not for security oriented ones.

    ReplyDelete
  5. Hi Shakyamoony,
    Could you kindly cite an example where as you mentioned it would not work? I would like to know and update the code appropriately.
    Thanks!

    ReplyDelete
  6. I think shakyamoony means that you need to have a random file name for security issues.

    ReplyDelete
  7. O noes, you not using proer camel casing for the public method always begin publics with a capital letter and camel case in c# =D. And your code is theoritically perfect ... shakyamoony probably dosnt understand what a GUID is, the way guids are designed they have part of a timestamp .... so, you would have to theoritically write a billion files per seccond to even remotely be likely to have a duplicate Guid =) Good Job

    ReplyDelete
  8. thanks for the code. It was useful.

    ReplyDelete
  9. This code does not guarantee that your temporary file will be removed after all.

    Bad code in any way.

    ReplyDelete
  10. This seems a reasonable solution. It is a big shame that the standard dot net GetTemporaryFile function will not let you specify an extension.

    ReplyDelete
  11. You should be using Path.GetTempFileName(). This creates you a unique file that will be destroyed.
    If you're using a temporary file you should not care about its extension.
    i.e.
    public void SaveFile(){

    var temp_filename = Path.GetTempFileName();

    if(!MyWriteMethod(tmp_filename)) return;

    var ofd = new OpenFileDialog { Filter = "XML Files|*.xml|All Files|*.*", };

    if (!ofd.ShowDialog()) return;

    File.Copy(temp_filename, ofd.FileName);
    }

    ReplyDelete
  12. @shakyamoony Yeah really security minded you must be. From the MSDN Docs..

    The GetTempFileName method will raise an IOException if it is used to create more than 65535 files without deleting previous temporary files.

    65K Files? I would *rather* use a GUID..

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.