@SLaks has a basic algorithm, but you need to keep in mind the race conditions. A file can be created by another thread or process during the time between checking File.Exists and creating the file. Here is a solution scheme based on the SLak algorithm:
FileStream fileCopy; while(File.Exists(actualName) || Directory.Exists(acutalName)) { actualName = baseName + " (" + (++index) + ")"; try { fileCopy = new FileStream(actualName, FileMode.CreateNew); } catch (IOException) { if (!File.Exists(actualName)) { throw; } } }
If you are unable to open the file, this happens either because some other process created the file, or because of some unexpected problem. Repeat throwing exceptions in case of unexpected problem (never swallow unexpected exceptions.)
You could simply use whether the “new FileStream” operation throws an exception as a loop condition, but I avoid throwing exceptions for error-free conditions. This makes it harder to use the “broken” behavior of exceptions in the debugger, and exceptions are expensive calculations. I assume that it is not a mistake in the context of your application to have a file in the file system with the same name that you would like to use for your copy. If I am mistaken about this, then the exception if the file exists is appropriate in my mind.
source share