0

I know that pretty much every programming language has a method to check the existence of a file or directory.

However, in my case, a file is made which stores program settings. If it does not exist (ie !File.Exists or Directory.Count == 0 where Directory is the containing directory of the file), then prompt for some settings to be filled in.

However, is this sort of code reliable? For example, there may be no files in the directory in which case the details are requested, otherwise there may be files of other types which are irrelevant or a tampered file of the correct format. Would it be better to check for the specific file itself? Would it also be better to check for variables which make up the file as this is faster?

What is the best general way of doing this? Check a file, if the folder is there? If the folder is there and empty? Check the strings which are written to the file?

EDIT: A school of thought from a colleague was that I should check at the variable level because it would be closer to the problem (identify issues like incorrect encryption, corruption, locales, etc).

Thanks

JohnFx
  • 34,542
  • 18
  • 104
  • 162
GurdeepS
  • 65,107
  • 109
  • 251
  • 387
  • are multiple threads/clients checking it simultaneously? I would think that plays in. – Aaron Anodide Oct 21 '10 at 23:02
  • 1
    Why *wouldn't* you simply check for the existence of the precise file? Why would you do the `Directory.Count == 0` check at all? – Kirk Woll Oct 21 '10 at 23:02
  • hopefully not... reading the same file from multiple threads is horrible program design. – Sam Dufel Oct 21 '10 at 23:04
  • @Sam Dufel - as long as it's secured with proper locks, I see no problem. Especially if this is a shared configuration file on a network share. Within the same process it would, of course, make sense to cache the results for performance reasons, but reading them every time is no crime either. It does not say anything about code quality. – Vilx- Oct 21 '10 at 23:06
  • Good point - I was thinking more of a local application with multiple threads checking settings from a config file, rather than managing settings in a synchronized object. – Sam Dufel Oct 21 '10 at 23:15

2 Answers2

2

I'd just check for the existence and validity of the specific file. If you encounter a corrupted file, get rid of it and make a new one.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
0

For basic development, it is purely choice. In the case where the file existing is crucial to the stability of the application, checking the file directly is the safest route.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144