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;
}
very useful thanks
ReplyDeleteN
No need to invent what's been provided by the runtime. Take a look at:
ReplyDeletePath.GetTempFileName()
Mike
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?
ReplyDeletePath.ChangeExtension
ReplyDeleteThis code does not guarantee that you have unique filename. This will work for 99% of regular buggy applications, but not for security oriented ones.
ReplyDeleteHi Shakyamoony,
ReplyDeleteCould you kindly cite an example where as you mentioned it would not work? I would like to know and update the code appropriately.
Thanks!
I think shakyamoony means that you need to have a random file name for security issues.
ReplyDeleteO 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
ReplyDeletethanks for the code. It was useful.
ReplyDeleteThis code does not guarantee that your temporary file will be removed after all.
ReplyDeleteBad code in any way.
This seems a reasonable solution. It is a big shame that the standard dot net GetTemporaryFile function will not let you specify an extension.
ReplyDeleteYou should be using Path.GetTempFileName(). This creates you a unique file that will be destroyed.
ReplyDeleteIf 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);
}
@shakyamoony Yeah really security minded you must be. From the MSDN Docs..
ReplyDeleteThe 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..