johnc
johnc

Reputation: 40223

C# How costly is Directory.Exists

Is it a bad idea to ensure that a log directory exists before every log message in an application that could be logging a few times a second (though not continually)?

I could implement a File System Watcher style thread to fire up and recreate a lost log directory, but my gut feeling is that would be a bit heavier an operation

Upvotes: 1

Views: 750

Answers (2)

JP Alioto
JP Alioto

Reputation: 45127

Probably not that expensive. If you did it by just handling the exception on the failed write, you would only get the exception the first time through (or after the directory is removed) and then everything else would be straight through. That might be better than continually checking.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190986

I would check to see if it exists on the first time, such as the construction of your logger, if not create it then.

Windows cannot easily delete a directory that is in use.

Upvotes: 4

Related Questions