When is it okay to check if a file exists?

前端 未结 18 2294
再見小時候
再見小時候 2020-11-28 06:52

File systems are volatile. This means that you can\'t trust the result of one operation to still be valid for the next one, even if it\'s the next line of code. You can\'t

18条回答
  •  独厮守ぢ
    2020-11-28 07:13

    I think the check makes sense when you want to be sure the file was there in the first place. As you said settings files...if there is a file I will try and merge the existing settings instead of blowing them away.

    Other cases would be when a user tells me to do something with a file. Yes I know the openFileDialog will check if a file exists (But this is optional). I vaguely remeber back in VB6 this was not the case, so verifying the file existed that they just told me to use was common.

    I'd rather not program by exception.

    Edit

    I didn't miss the point. You might try and access the file, an exception is thrown and then when you go to create the file, the file was already placed there. Which now causes your exception handling code to go on the fritz. So I guess we could then have an exception handler in our exception handler to catch that the file changed yet again...

    I'd rather try and prevent exceptions, not use them to control logic.

    Edit

    Additionally another time to check for attributes such as size is when your waiting for a file operation to finish, yes you never know for sure but with a good algorithim and depending on the system writting the file you might be able to handle a good deal of cases (Had a system running for five years which watched for small files coming over ftp, and it uses a the same api as the file system watcher, and then starts polling waiting for the file to stop changing, before raising an event that the file is ready to be consumed).

提交回复
热议问题