How to quickly check if folder is empty (.NET)?

后端 未结 18 860
旧时难觅i
旧时难觅i 2020-12-02 08:22

I have to check, if directory on disk is empty. It means, that it does not contain any folders/files. I know, that there is a simple method. We get array of FileSystemInfo\'

18条回答
  •  执笔经年
    2020-12-02 08:56

    I'm sure the other answers are faster, and your question asked for whether or not a folder contained files or folders... but I'd think most of the time people would consider a directory empty if it contains no files. ie It's still "empty" to me if it contains empty subdirectories... this may not fit for your usage, but may for others!

      public bool DirectoryIsEmpty(string path)
      {
        int fileCount = Directory.GetFiles(path).Length;
        if (fileCount > 0)
        {
            return false;
        }
    
        string[] dirs = Directory.GetDirectories(path);
        foreach (string dir in dirs)
        {
          if (! DirectoryIsEmpty(dir))
          {
            return false;
          }
        }
    
        return true;
      }
    

提交回复
热议问题