I need to copy some files to a directory, but sometimes this directory does not exist yet and must be created first. In most cases, the directory will exist, although it must be created only once.
I know that I can just put Directory.CreateDirectory() before the copy of the file, and CreateDirectory() will just return if the directory already exists.
string destFolder; // path to destination string sourceFolder; // path to source Directory.CreateDirectory( destFolder ); // this will work even if destFolder exists File.Copy( sourceFolder + sourceFileName, destFolder + sourceFileName );
But I know that in almost every case, the destination folder already exists, so itβs faster to check if it exists first and not to call CreateDirectory() in any case.
if( !Directory.Exists( destFolder ) ) // check if it exists first { Directory.CreateDirectory( destFolder ); } // now move on to using the folder
I don't care how long it takes to create a directory, given that users will only do this once. I'm more interested in whether the if works with Directory.Exists() faster than the time it takes for Directory.CreateDirectory() to find out if the directory already exists.
"It seems to me that it is" wasteful "to call Directory.CreateDirectory() every time, although it probably exists, so I first" feel better ", but it still calls the function anyway, so I really get advantage of extinction - does my code with additional if and Directory.Exists() operators check?
source share