When is it okay to check if a file exists?

前端 未结 18 2384
再見小時候
再見小時候 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:22

    I think the reason for "Exists" is to determine when files are missing without the need for creating all the OS housekeeping data required to access the file or having exceptions being thrown. So it's a file handling optimisation more than anything else.

    For a single file, the saving the "Exists" gives is generally insignificant. If you were checking if a file exists many, many times (for example, searching for #include files) then the saving could be significant.

    In .Net, the specification for File.Exists doesn't list any exceptions that the method might throw, unlike for example File.Open which lists nine exceptions, so there's certainly less checking going on in the former.

    Even if "Exists" returns true, you still need to handle exceptions when opening the file, as the .Net reference suggests.

提交回复
热议问题