Using IsolatedStorage, Is it necessary to check if a directory exists before creating it?
I'm working on a Windows Phone 7 app, and I was wondering whether anyone had a definitive answer on whether or not I have to check if a directory exists before creating one, and what the advantages/disadvantages of doing/not doing so are. As far as I can tell, from stepping through my code, the following two blocks of code work in the same man开发者_JAVA百科ner:
using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//ensure directory exists
String sDirectory = System.IO.Path.GetDirectoryName(sPath);
if (!appStorage.DirectoryExists(sDirectory))
{
appStorage.CreateDirectory(sDirectory);
}
}
and
using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//ensure directory exists
String sDirectory = System.IO.Path.GetDirectoryName(sPath);
appStorage.CreateDirectory(sDirectory);
}
Is it safe to use the second block of code? It didn't seem to throw an exception if the directory already existed, and also seemed to leave the contents of the directory alone.
The IsolatedStorageFile.CreateDirectory
will call Directory.CreateDirectory
internally. The documentation of Directory.CreateDirectory
states:
If the directory already exists, this method does nothing.
In other words, you don't need to check if that directory exists. The method already does that for you.
I suspect that internally CreateDirectrory
is doing a check if the directory already exists or is swallowing an exception. Either way, there is probably a small performance benefit to be had from calling DirectoryExists
explicitly before hand.
The way to test for sure would be to benchmark performance of the 2 methods with creating a large number of directories. (If you try this, be aware that you can't have more than 16k directories in a parent directory and you can't go more than 18 (I think) directories deep.)
It's better practice to be explicit about what you're doing. I would hope that any other developer who looked at the code would ask you you weren't testing for existence before creating a directory. Especially if this code was called many times. If you test and find no difference in performance, I'd recommend a comment in the code to state this.
精彩评论