【问题标题】:C# Why is my code throwing a io.system.directorynotfound?C# 为什么我的代码会抛出 io.system.directorynotfound?
【发布时间】:2009-03-23 13:50:02
【问题描述】:

为什么下面的代码会抛出 io.system.directorynotfound 异常?我自己无法重新创建问题,但我的代码的另一个用户确实看到了它,有什么想法吗? 谢谢

try
{
  //create path
  string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
  //check path exists
  if (!System.IO.File.Exists(strAppData))
  {
      System.IO.Directory.CreateDirectory(strAppData);
  }
  System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
  int count = dir.GetFiles().Length;

  if (count > 100)
  {
      string[] files = System.IO.Directory.GetFiles(strAppData);

      foreach (string file in files)
      {
          System.IO.File.Delete(file);
      }
  }


  this.fileName = fileName;
  // delete the file if it exists
  if (File.Exists(fileName))
  {
      //delete the file
      File.Delete(fileName);
  }

      // write the data to the file
      fs = File.OpenWrite(fileName);
      sWriter = new StreamWriter(fs);

      sWriter.WriteLine(headerText);

      sWriter.Flush();
      sWriter.Close();
}
catch (Exception exp)
{
    throw new Exception(exp.Message);
}

【问题讨论】:

    标签: c# directory


    【解决方案1】:

    在检查路径是否存在时,您是否尝试过使用 System.IO.Directory.Exists 而不是 System.IO.File.Exists?

    【讨论】:

      【解决方案2】:

      您正在使用System.IO.File 而不是System.IO.Directory 检查目录是否存在。它可能适用于您的计算机,因为该目录已经存在,因此检查无关紧要。

      无论哪种方式,您都需要记住文件系统是易失的。与其检查是否存在,不如尝试打开资源并在失败时处理异常。

      【讨论】:

        【解决方案3】:

        检查目录是否存在,而不是文件...

        虽然您正在检查它,如果它不存在则创建它。您不知道他们是否有创建目录的权限。因此,您的 Directory.CreateDirectory 调用很可能也失败了,然后其余代码将失败

        【讨论】:

          【解决方案4】:

          http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

          "备注

          Exists 方法不应用于路径验证,该方法仅检查路径中指定的文件是否存在。将无效路径传递给 Existsl 将返回 false。 "

          那是你的错误。您的验证不能确保文件的路径存在

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-07-15
            • 2021-03-13
            • 1970-01-01
            • 2017-07-08
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多