Michael Michael - 3 months ago 23
C# Question

How to find the file by its partial name?

How can I get the full filename?

For example:

I have a file named

171_s.jpg
that is stored on the hard disc.

I need to find the file by its partial name, i.e.
171_s
, and get the full name.

How can I implement this?

Answer

Here's an example using GetFiles():

static void Main(string[] args)
    {
        string partialName = "171_s";

        DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
        FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");

        foreach (FileInfo foundFile in filesInDir)
        {
            string fullName = foundFile.FullName;
            Console.WriteLine(fullName);
        }

    }
Comments