I
I
itgood2019-03-31 12:19:22
C++ / C#
itgood, 2019-03-31 12:19:22

How to make it not count system folders?

there is a code you need to get all text files on all drives, my code counts system folders and an error pops up

try
      {
        string[] allFoundFiles=null;
        foreach (var item in Drives)
        {
          allFoundFiles = Directory.GetFiles(item, "*.txt", SearchOption.AllDirectories);


          foreach (string file in allFoundFiles)
          {
            row = table.NewRow();
            str = file.Split('\\');

            row["Название"] = str[1];
            row["Путь"] = str[0];

            table.Rows.Add(row);

          }
        }

How can I bypass these folders?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
itgood, 2019-03-31
@itgood

If anyone is interested here is the solution.

public  IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern, SearchOption searchOption)
    {

      Stack<string> dirs = new Stack<string>();
      dirs.Push(path);

      while (dirs.Count > 0)
      {
        string currentDirPath = dirs.Pop();
        if (searchOption == SearchOption.AllDirectories)
        {
          try
          {
            string[] subDirs = Directory.GetDirectories(currentDirPath);
            foreach (string subDirPath in subDirs)
            {

              if ((File.GetAttributes(subDirPath) & (FileAttributes.Hidden | FileAttributes.System)) != (FileAttributes.Hidden | FileAttributes.System))
              {
                dirs.Push(subDirPath);
              }
            }
          }
          catch (UnauthorizedAccessException)
          {
            continue;
          }
          catch (DirectoryNotFoundException)
          {
            continue;
          }
        }

        string[] files = null;
        try
        {
          files = Directory.GetFiles(currentDirPath, searchPattern);
        }
        catch (UnauthorizedAccessException)
        {
          continue;
        }
        catch (DirectoryNotFoundException)
        {
          continue;
        }

        foreach (string filePath in files)
        {
          yield return filePath;
        }
      }
    }

L
Larisa .•º, 2017-01-12
@Deonnis3

why check the length, it's not easier

if (value == '') {hide}
 else {show}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question