create a regular expression based on the names of files in a folder in csharp

You can use the Regex class in C# to create a regular expression based on the names of files in a folder. Here is an example of how to do this:

main.cs
using System;
using System.IO;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // Set the folder path
        string folderPath = @"C:\Users\Username\Documents\TestFolder";

        // Set the regular expression pattern
        string pattern = @"^File\d{3}\.txt$"; // Example: File001.txt, File002.txt

        // Get the files in the folder that match the pattern
        string[] files = Directory.GetFiles(folderPath)
                                   .Where(path => Regex.IsMatch(Path.GetFileName(path), pattern))
                                   .ToArray();

        // Do something with the files
        foreach (string file in files)
        {
            Console.WriteLine(file);
        }
    }
}
755 chars
27 lines

In this example, the regular expression pattern is set to match file names that start with "File" followed by three digits and ending with ".txt". You can modify the pattern to match the naming convention of your files. The Directory.GetFiles method is used to get all the file paths in the specified folder, and Regex.IsMatch is used to check if the file name matches the pattern. The resulting array contains only the file paths that match the pattern.

gistlibby LogSnag