acadia
acadia

Reputation: 2621

Search fileName and get full path based on a pattern in C#

How do I get the full path for a file based on first 6 letters in the filename in C#? Is there any Regex for this?

I have a folder with 500K+ images. All the images are named as per the database column value. I am querying the table and based on the column value I have to search the folder for the specific file.

If the column value is 209050 there will be one file in the folder like 209050.pdf or 209050_12345.pdf. There will always be one image for 209050.

Please help

Upvotes: 0

Views: 4515

Answers (2)

Amith George
Amith George

Reputation: 5916

var files = Directory.EnumerateFiles(@"C:\MyRootDir", "209050*", SearchOption.AllDirectories);

This will return an enumerable of strings. Each string will the full path of the file whose name matches the specified pattern, in this case, any file whose name begins with '209050', irrespective of the extension. This will even search within sub directories of the folder MyRootDir.

If you wish to only filter for jpg files, change the 2nd argument accordingly.

var files = Directory.EnumerateFiles(@"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);

In case you are NOT using .Net Framework 4 or 4.5, you could use the GetFiles method instead.

var files = Directory.GetFiles(@"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);

Upvotes: 1

JMK
JMK

Reputation: 28080

The following will show you all .jpg files starting with 209050 in C:\MyDirectory:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] myFiles = Directory.GetFiles(@"C:\MyDirectory");

            foreach (var x in myFiles)
            {
                string[] splitName = x.Split('\\');
                string fileName = splitName[splitName.Length - 1];

                if (fileName.StartsWith("209050") && fileName.EndsWith(".jpg"))
                {
                    Console.WriteLine(x);
                }
            }

            Console.ReadLine();
        }
    }
}

Here is my directory:

My Directory

Here is the output:

Output

Does this help?

Upvotes: 0

Related Questions