I came across a curious piece of code as I was working my way through the project I work day-in-day-out on; not that curious pieces of code are rare in this project.
This one made me stop and think. I knew it was wrong, but how could I make it right? The problem is how to determine a unique filename in a directory, say for example if I wanted to allow users to upload images which would be stored in a folder, I don't want to overwrite existing files and I don't want to use the filename of the uploaded file.
Here's the code I came across.
1int count = 1; 2while (count < 1000) 3{ 4 string tmp = Path.Combine(this.ImagesPhysicalFolder, modifiedFileName) + count.ToString() + ".jpg"; 5 if (!File.Exists(tmp)) 6 { 7 modifiedFileName = tmp; 8 break; 9 } 10 ++count; 11}
It's a little verbose, and calling the Path.Combine()
inside the loop could be costly. This is the solution I came up with.
1var root = ...; 2 3/* snip */ 4 5var count = 0; 6var template = Path.Combine(root, "file_%%.jpg"); 7var filename = template.Replace("%%", (count++).ToString()); 8while (File.Exists(filename)) 9{ 10 filename = template.Replace("%%", (count++).ToString()); 11}