Hi. In my project I need to check if a specific file exists before I try to load it and perform some operations on it in runtime.
Using (System.IO.File.Exists(dir)) method works, however, for some reason it’s very slow and takes up to one second. I’d say that’s definitely too long to make any sense considering that the operation triggered by this condition lasts for less than a millisecond.
Are there any faster methods of checking if a file exists?
I’ve been thinking about preparing a file list at program launch, which would make runtime operations faster, as the condition would then compare with a value from the memory. But that would be sweeping the problem under the carpet instead of getting rid of it.
It’s a local file. Anyways, I found factors which were the cause:
Searching for files with characters like “-” and “_” in the file name drastically raise the search time for some reason.
Looking for a file that doesn’t exist takes a lot of time, which makes sense, as the routine probably has to check everything in the folder.
When there are lots of files in the folder (few thousands in my case) the search additionally slows down.
Eventually I’ve decided to list all files with Directory.GetFiles() at program launch and put their shortened names into a dictionary. Now single search takes about 0.000007 seconds.
I guess it was my fault that I was trying to use method which obviously wasn’t suited for such use. But, hey, at least I learned something new today.