【问题标题】:DirectoryNotFound Exception in C#C# 中的 DirectoryNotFound 异常
【发布时间】:2011-07-06 18:51:06
【问题描述】:

我正在尝试将文件保存在路径 WindowsFormsApplication1\WindowsFormsApplication1\SaveFile 但以下代码返回“DirectoryNotFound”异常并显示消息:

找不到路径的一部分 'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx

String Path = @".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
    using (StreamWriter writer = info.CreateText())
    {
        writer.WriteLine("HELLO");
    }
} 

谁能告诉我应该如何在指定完整路径的情况下将文件保存在我想要的文件夹中?

【问题讨论】:

  • 错误的级别太多了。如果您不想指定要保存文件的文件夹,如何将文件保存到文件夹中?
  • 我想将我的文件保存在“WindowsFormsApplication1\WindowsFormsApplication1\SaveFile”文件夹中,并指定完全合格的 URL。
  • @Stardust:那么你需要运行应用程序,当前目录设置为“D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1”。
  • 在写入之前,您甚至不会尝试验证目录是否存在。

标签: c# .net path


【解决方案1】:

当您在调试器中运行时,您的默认路径在bin\Debug 下。那就是“。”意味着在你的道路上。

您要保存到哪个文件夹?您需要指定完整路径。也许您想从配置文件中提取路径。这样,路径将能够根据您的应用程序的部署位置进行更改。

【讨论】:

    【解决方案2】:

    正如错误消息告诉您的那样,该文件将保存在 bin/debug 下的子目录 SaveFile 中。在保存文件之前,您必须使用 Directory.CreateDirectory("SaveFile") 创建一个目录。它不会自动创建。

    【讨论】:

      【解决方案3】:

      在创建文本文件之前,您需要确保目录存在。

      String Path = @".\SaveFile\Hello.txt";
      FileInfo info = new FileInfo(Path);
      if (!info.Exists)
      {
          if (!info.Directory.Exists)
              info.Directory.Create();
      
          using (StreamWriter writer = info.CreateText())
          {
              writer.WriteLine("HELLO");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-17
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        相关资源
        最近更新 更多