Suppose I forget the full path of a file on my computer, but I remember the filename and a segment of the path.
example:
test
and the segment of the path that I sill remember is \\test1\\test2
So I would like to get the full path with c#, like this: C:\\test1\\test2\\test3\\test4\\test.txt
Thanks in advance!
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.
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);
}
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.