C# | How to select just a few subfolders?

Asked

Viewed 114 times

0

I need to search the information of only a few subfolders inside a main directory, I made a code this way but I’m having a hard time finding a way to inform only the subfolders I need. For example I have a folder in this structure:

Briefcase
|
|_ _ _ subfolder 1/.xml files
|
|_ _ _ subfolder 2/.xml files
|
|_ _ _ subfolder 3/.xml files

You’d need to get the data from subpasta1 and subpasta3, the code I have I can only read the Briefcase entire:

using System.IO;
using System;
using System.Linq;

namespace LerDiretorios
{
    class Program
    {
        static void Main(string[] args)
        {
            var directoryPath = @"C:\Pasta\";
            var searchPattern = "*.xml";
            var monthsAgo = -2;
            string[] filesFound;
            var startTime = DateTime.Now;

            try
            {
                filesFound = Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);

                filesFound
                    .Select(f => new FileInfo(f))
                    .Where(f => f.CreationTime >= f.CreationTime.AddMonths(monthsAgo))
                    .ToList();
            }
            catch (Exception ex)
            {
                Console.Write($"ERRO: {ex.Message}");
                goto End;
            }

            if (filesFound.Length == 0)
            {
                Console.WriteLine("Nenhum arquivo encontrado.");
                goto End;
            }

            foreach (string filePath in filesFound)
            {
                FileInfo fInfo = new FileInfo(filePath);
                Console.WriteLine(
                    $"{fInfo.Directory}, Arquivo: {Path.GetFileName(fInfo.Name)}, " +
                    $"Criado em: {fInfo.CreationTime.ToString()}\n");
            }

            //Conta os registros lidos
            Console.WriteLine($"Quantidade de registros lidos: {filesFound.Length}");

            //Mostra hora de início do procedimento
            Console.WriteLine($"Hora Inicio: {startTime.TimeOfDay}");

            //Mostra hora de fim do procedimento
            var finishTime = DateTime.Now; 
            Console.WriteLine(
                $"Hora Fim: {finishTime.TimeOfDay} \n" +
                $"Tempo de Execução: {finishTime.TimeOfDay - startTime.TimeOfDay}");

        End:;
        }
    }
}
  • It has so many shapes but nothing direct has to pass the Path in this case apart since you know which one you want to read. Create an array with folder names and do a for. I ask is multiple folders?

  • Like you would if it wasn’t programming?

  • 1

    @Virgilionovic are almost 60 sub-folders, I simplified a little in the example, but the logic I think would be the same to solve. I’ll try it on and see how it looks.

1 answer

2


Note: Your code can be refactored and enhanced, because you can for example create the list of Fileinfo directly by the class Directoryinfo

If you want to specify only some directories to list your files depending on the type use an argument from array informing which folders need to search, also worth remembering that there is already a way to return Fileinfo explicitly follows the example below::

This method first return a array of Fileinfo:

private static FileInfo[] GetFiles(string[] paths, string search = "*.xml")
{
    FileInfo[] items = null;
    foreach (string path in paths)
    {
        if (Directory.Exists(path))
        {
            items = (items == null)
                ? (new DirectoryInfo(path)).GetFiles(search)
                : items.Concat((new DirectoryInfo(path)).GetFiles(search)).ToArray();
        }
    }
    return items;
}

And this other method prints out the file information:

private static void PrintFileInfo(FileInfo[] fileInfos)
{
    if (fileInfos != null)
    {
        foreach (FileInfo fileInfo in fileInfos)
        {
            Console.WriteLine(
             $"{fileInfo.DirectoryName} Arquivo: {fileInfo.Name}, " +
             $"Criado em: {fileInfo.CreationTime.ToString("dd/MM/yyyy HH:mm:ss", null)}\n");
        }
    }
    else
    {
        Console.WriteLine("Nenhum dado para impressão");
    }
}

always try to divide in a logical way that each thing does, one takes the files the other shows the files and so on, the reuse becomes clearer.


How to use?

// Busca os arquivos
FileInfo[] items = GetFiles(new string[] { @"C:\", @"D:\" }, "*.txt");

//Mostra os arquivos com as suas informações
PrintFileInfo(items);

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.