C# -Why does System.IO.File.GetLastAccessTime return an expected value when the file is not found?

后端 未结 6 1758
野性不改
野性不改 2021-01-04 06:05

Please, explain your thoughts.

1.  DateTime dt = System.IO.File.GetLastAccessTime(\"C:\\\\There_is_no_such_file.txt\");
2.  DateTime dt = System.IO.File.Get         


        
6条回答
  •  佛祖请我去吃肉
    2021-01-04 06:46

    We're dealing with two different things.

    When you call a method with an invalid argument, it should throw an exception.

    If the file doesn't exist, this is not necessarily an exception. Therefore, a default value is returned, which you can test and decide how to proceed. For the GetLastAccessTime method, it isn't critical that the file exists. If it is critical for YOUR code, then you should be responsible for generating an error...

    if (!File.Exists("C:\\There_is_no_such_file.txt")) {
        throw new FileNotFoundException();
    }
    

提交回复
热议问题