简体   繁体   中英

C# List files in current directory with matching regex pattern in an array

I have three text files in my directory:

login.txt
43.txt
100001.txt

I would like to keep an array of all filenames in the current directory which have a naming convention of any number (up to six digits in length) followed by ".txt" as the file name.

I have tried this:

            Regex pattern = new Regex(@"^[0-9]{1,6}$");
            string path = Directory.GetCurrentDirectory();
            
            string[] files = Directory.GetFiles(path, "*.txt")
                     .Where(path => pattern.IsMatch(path)).ToArray();

            foreach (var myFile in files)
            {
                try
                {
                    Console.WriteLine("Filename:" + myFile);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

But it isnt finding my files at all.

What is the correct approach to this?

Thanks in advance.

Regex  pattern = new Regex(@"^[0-9]{1,6}\.txt$", RegexOptions.IgnoreCase);
string path    = @"c:\Temp\1\";

string[] files = Directory.GetFiles(path, "*.txt")
    .Where(path => pattern.IsMatch(Path.GetFileName(path))).ToArray();

foreach (var myFile in files)
{
    try
    {
        Console.WriteLine("Filename:" + myFile);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM