Ejercicio
Subdirectorios
Objetivo
Cree un programa para almacenar los archivos que se encuentran en un determinado directorio y sus subdirectorios.
Luego, le preguntará al usuario qué texto buscar y mostrará los archivos que contienen ese texto en su nombre.
El programa finalizará cuando el usuario introduzca una cadena de búsqueda vacía.
Código de Ejemplo
// Importing necessary namespaces
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Subdirectories
{
// Main method where the program execution starts
static void Main()
{
Console.WriteLine("Enter the directory path to scan:");
string directoryPath = Console.ReadLine(); // Ask the user for the directory path
if (!Directory.Exists(directoryPath))
{
Console.WriteLine("The directory does not exist. Please try again with a valid path.");
return;
}
// Store files and subdirectories
List filesList = GetFilesInDirectoryAndSubdirectories(directoryPath);
// Loop for searching files by name
while (true)
{
Console.WriteLine("\nEnter the text to search in file names (leave empty to exit):");
string searchText = Console.ReadLine(); // Get the search text from user
if (string.IsNullOrWhiteSpace(searchText))
{
Console.WriteLine("Exiting the program.");
break; // Exit the program if the search string is empty
}
// Search for files that contain the search text in their names
var matchedFiles = filesList.Where(f => f.Contains(searchText, StringComparison.OrdinalIgnoreCase)).ToList();
// Display the matching files
if (matchedFiles.Any())
{
Console.WriteLine("\nFiles containing the search text:");
foreach (var file in matchedFiles)
{
Console.WriteLine(file);
}
}
else
{
Console.WriteLine("\nNo files found containing the search text.");
}
}
}
// Method to get all files from a directory and its subdirectories
static List GetFilesInDirectoryAndSubdirectories(string path)
{
List files = new List();
// Get all files in the current directory
files.AddRange(Directory.GetFiles(path));
// Get all subdirectories in the current directory
var subdirectories = Directory.GetDirectories(path);
// Recursively get files from subdirectories
foreach (var subdir in subdirectories)
{
files.AddRange(GetFilesInDirectoryAndSubdirectories(subdir));
}
return files;
}
}