【问题标题】:WriteAllText doesn't seem to get called [duplicate]WriteAllText 似乎没有被调用[重复]
【发布时间】:2013-09-11 15:40:07
【问题描述】:
I am trying to save GetDirectories as a txt file, but somewhere my program fails.

private void Form1_Load(object sender, EventArgs e)
{

    var directoryInfo  = new System.IO.DirectoryInfo(@"g:\FTP\");
    int directoryCount = directoryInfo.GetDirectories().Length;

    ...        

    var directoryInfo11  = new System.IO.DirectoryInfo(@"q:\FTP\");
    int directoryCount11 = directoryInfo11.GetDirectories().Length;

    int directoryCountMain = directoryCount + directoryCount2 + 
        directoryCount3 + directoryCount4  + directoryCount5 + 
        directoryCount6 + directoryCount7  + directoryCount8 + 
        directoryCount9 + directoryCount10 + directoryCount11;

    string text = "Total Releases: ";

    // WriteAllText creates a file, writes the specified string to the 
    // file, and then closes the file.
    System.IO.File.WriteAllText(@"c:\test\ik.txt", text + directoryCountMain);
}

I don't get an error or anything, It looks like my code is skipped as I tried placing a MessageBox.Show below the code but It got ignored.

【问题讨论】:

  • 你把消息框放在哪里了?多解释一下你的问题。
  • 最后,我想要的只是从硬盘驱动器中获取所有文件夹并将数量保存在 txt 文件中,但我什么也没得到。
  • 它看起来被跳过可能是因为它被跳过了 - 验证Load event 确实被订阅了。
  • 调试它。逐步完成。

标签: c#


【解决方案1】:

我认为您提供的此目录和路径不存在或错误,因此在尝试获取信息时抛出异常

var directoryInfo11 = new System.IO.DirectoryInfo(@"q:\FTP\");

在你的代码周围添加 try catch 块,看看它是否抛出异常。

【讨论】:

    【解决方案2】:

    在 Form1_Load 的第一条语句上放置一个断点,看看它是否被命中。如果没有,您可能需要在代码中订阅此事件。

    如果它被击中,单步执行你的代码并找到它失败的那一行。

    注意Form_Load does not catch exceptions by default,所以它看起来好像其他行被跳过了。有办法解决的,点上面的链接就好了。

    【讨论】:

      【解决方案3】:

      这不会解决您的问题,但至少会缩短您的代码并使其可维护。用下面的代码替换你的代码,它会做同样的事情。

      var ftpDirs = new string[] { "g:/FTP/", ... };
      int subDirsCount = 0;
      
      foreach(var dir in ftpDirs)
      {
          subDirsCount += new DirectoryInfo(dir).GetDirectories().Length;
      }
      
      string text = "Total Releases: ";
      File.WriteAllText(@"c:\test\ik.txt", string.Format("{0}{1}", text, subDirsCount));
      

      不要忘记在文件顶部添加以下内容。

      using System.IO;
      

      【讨论】:

      • 请回答问题
      • @DavidHeffernan 我的答案不是我在 cmets 中提供的答案类型。它足够长,值得在其他答案中占有一席之地。我在那里说过,这不是一个直接的答案,而只是一个有用的想法。
      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多