【问题标题】:what will happen if file not exist如果文件不存在会发生什么
【发布时间】:2015-12-22 10:27:37
【问题描述】:

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

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

如果文件不存在会怎样?

【问题讨论】:

  • 试试看你得到了什么错误..你忘记了c#-5.0标签
  • 您在查看the documentation 时看到了什么? Stack Overflow不是研究的替代品。

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


【解决方案1】:

正如Here 提到的,当文件不存在时打开文件会抛出FileNotFoundException。因此,要让它发挥作用:

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

甚至:

try{
   using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open))
      {
      //code
      }
}
catch(FileNotFoundException e)
{
      //code
}

因为我讨厌那些评论“google it!”的人。 “在文档中查找”尽管这是典型的文档搜索,但我还是决定回答这个问题。堆栈应该是关于问答的。

【讨论】:

    【解决方案2】:

    除了上面的答案,它也可能抛出UnauthorizedAccessException

    【讨论】:

    • 欢迎来到 Stack Overflow!虽然这在理论上可以回答问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2019-07-24
    • 1970-01-01
    • 2016-07-13
    • 2020-03-13
    • 2021-04-08
    相关资源
    最近更新 更多