Code Review: GetTempFileName in C#


Code Review is very important, because it will help to get rid of those low quality code, which may not be easily identified. The low quality code may pass the test cases but still error-prone.

The following code intents to get a unique temporary file name. It gets the temp folder by function Path.GetTempPath(). The Path.GetRandomFileName() function returns a random (cryptographically strong no less) file name.

GetTempFileName Code Review: GetTempFileName in C# c # code programming languages

GetTempFileName

However, this code looks quite ugly. First, it generates a random file name and checks if it is existent. If it is, then do the while loop until a random file name is not in use or it reaches 100 times. In the while loop condition, there is a check for null or empty but this is always false (unnecessary) from the second time.

In C# (.NET), the Path.GetTempFileName() function creates a random unique file and return the file name. Why create the file? Because, in this way, the [race condition] will be avoided. If you just return a file name, then it is possible that several threads will return the same filename, and this way, it is not right.

Creating the file means that file name is reserved. Thus, other processes will not return the same file name, and this solves the [race condition]. The ugly code listed above intents to get the file name and then creates a temp file, which is really unnecessary. I have not seen situations that you get a unique temp file without having to create it.

The combination of Path.GetRandomFileName() and Path.GetTempPath() is more practical (does not create file):

1
2
3
4
public static string GetTempFileName()
{
    return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
public static string GetTempFileName()
{
    return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
374 words
Last Post: Important Configurations in WordPress Configuration File [wp-config.php]
Next Post: How to Disable Onboard Graphics Card?

The Permanent URL is: Code Review: GetTempFileName in C#

Leave a Reply