Tuesday, April 1, 2008

How to receive temporary path and file name (c#).

    To receive standard Windows temporary path we can use c# method Path.GetTempPath().

To receive uniquely temporary file we can use method Path.GetTempFileName(). The method creates a zero-byte in temporary folder and returns a full path of that file. Path of the file is created by format: <temporary folder>\tmp<4 hex symbols>.tmp (for example, <temporary folder>\tmpF1FB.tmp).

   Let's investigate how a method GetTempFileName creates a uniquely temp file:

string tempFolder = Path.GetTempPath();
string uniqueTempFileName = Path.GetTempFileName();
string tempFolder_via_Environment = Environment.GetEnvironmentVariable("TEMP");

Debug.WriteLine("tempFolder: " + tempFolder);
Debug.WriteLine("tempFolder_via_Environment: " + tempFolder_via_Environment);
Debug.WriteLine("uniqTempFileName: " + uniqueTempFileName);

for (int i = 0; i < 0xFFFF; i++)
uniqueTempFileName = Path.GetTempFileName();
Debug.WriteLine("uniqTempFileName: " + uniqueTempFileName);
Debug.WriteLine(String.Format("File {0} exists: {1}", uniqueTempFileName, File.Exists(uniqueTempFileName)));
Output Window:


So, we can see rule, how GetTempFileName builds file name: "tmp" + counter + ".tmp". If a  file with next temporary file name exists, then GetTempFileName will generate next temporary file name.

File with name tmp3DBA.tmp was created manually and see result (tmp3D9, tmp3DBB) in Output Window


When all temporary names will be created, that exception IOException will be raised:



Path.GetTempPath Method

Path.GetTempFileName Method

No comments: