ilyes
ilyes

Reputation: 372

How to get the full path from a segment of a path and the filename in c#

Suppose I forget the full path of a file on my computer, but I remember the filename and a segment of the path.

example:

So I would like to get the full path with c#, like this: C:\test1\test2\test3\test4\test.txt

Thanks in advance!

Upvotes: 0

Views: 82

Answers (2)

Shayan Toqraee
Shayan Toqraee

Reputation: 867

You can go through all the files on the drive and check whether they match what you want: (This will be slow and resource consuming.)

var files = Directory.GetFiles(@"C:\", "test.txt", SearchOption.AllDirectories)
                     .Where(s => s.Contains(@"\test1\test2\"));
foreach (var f in files)
{
    Console.WriteLine(f);
}

Or you know the root directory in which you want to search, you can change it like this to be faster:

var files = Directory.GetFiles(@"C:\test1\test2", "test.txt", SearchOption.AllDirectories);
foreach (var f in files)
{
    Console.WriteLine(f);
}

Upvotes: 1

nicolas
nicolas

Reputation: 7668

If the segment you know is at the start of the path, you can do something like

DirectoryInfo f = new DirectoryInfo(@"C:\test1\test2");
var results = f.GetFiles("test.txt", SearchOption.AllDirectories);

If not, I'm afraid that you have to do a full search on the computer, and check if the result path contains your fragment.

Upvotes: 2

Related Questions