To search for all files with the extension .js
in all subdirectories of a given directory using C#, you can use the Directory
and File
classes from the System.IO
namespace. Here’s a C# code snippet to achieve that:
using System;
using System.IO;
class Program
{
static void Main()
{
string rootDirectory = @"C:\path\to\your\root\directory";
SearchJsFiles(rootDirectory);
}
private static void SearchJsFiles(string directoryPath)
{
try
{
// Get all files with .js extension in the current directory.
string[] jsFiles = Directory.GetFiles(directoryPath, "*.js");
foreach (string jsFile in jsFiles)
{
// Process the .js file (you can add your logic here).
Console.WriteLine(jsFile);
}
// Recursively search for .js files in subdirectories.
string[] subDirectories = Directory.GetDirectories(directoryPath);
foreach (string subDir in subDirectories)
{
SearchJsFiles(subDir);
}
}
catch (Exception ex)
{
// Handle any exceptions that may occur during the search.
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Replace C:\path\to\your\root\directory
with the actual path to the directory from which you want to start the search. The code will recursively search for all files with the .js
extension in all subdirectories and print their paths to the console.
Make sure that the provided directory path exists, and you have sufficient permissions to access the files within it. Additionally, remember that this code doesn’t perform any filtering based on the file content; it simply searches for files with the .js
extension. If you need to perform specific operations on the contents of the .js
files, you can modify the logic inside the foreach
loop accordingly.