如果文件不存在会发生什么

时间:2015-12-22 10:27:37

标签: c# c#-4.0 c#-3.0

我正在尝试访问不存在的文件。会抛出什么错误。?

using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open))
{
    // read from file or write to file
}

如果文件不存在会发生什么。?

2 个答案:

答案 0 :(得分:1)

如上所述Here文件不存在时打开文件会引发FileNotFoundException。因此要做到这一点:

Fetching: momentjs-rails-2.11.0.gem (100%)
Successfully installed momentjs-rails-2.11.0
19 gems installed

甚至:

var fileName = "c:\file.txt";
if(File.Exists(fileName)
{
      using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open))
{
      //code
}

因为我对像谷歌评论的人一样憎恨“google it!” “在文档中查找”我决定回答这个问题,尽管它是典型的文档搜索。堆栈应该是问答。

答案 1 :(得分:1)

除上述答案外,它也可能抛出UnauthorizedAccessException