I have a file path (it is a virtual file system path) and I want to find files with a name "test.txt" from parent dir. to its root dir/
string test = "test.txt" Let say I have a path : root/dir1/dir2/dir3/dir4/file.cs
Now, if I do
string parentDirectoryName = Path.GetDirectoryName(file); //Here I get dir4
string filePath = Directory.GetFiles(parentDirectoryName, test ).FirstOrDefault(); //I get the path of the text.txt if it is present or i get null.
But now, I want to go until root (and see if there is any file named test.txt) and if yes, get the path of all those files.
O/P should be List<string>
with all file paths from current dir. to root dir. for a file named "test.txt"
How to do that ?
CodePudding user response:
Try something like this out:
string test = "test.txt";
string somePath = @"C:\Users\mikes\Documents\Visual Studio 2017\Projects\CS_Scratch_WindowsFormsApp2\CS_Scratch_WindowsFormsApp2\Form1.cs";
FileInfo fi = new FileInfo(somePath);
List<string> testMatches = new List<string>();
DirectoryInfo di = fi.Directory;
while (di != null)
{
Console.WriteLine("Checking: " di.FullName);
string candidate = Path.Combine(di.FullName, test);
if (File.Exists(candidate))
{
testMatches.Add(candidate);
}
di = di.Parent;
}
Console.WriteLine("Matches:");
foreach(string path in testMatches)
{
Console.WriteLine(path);
}
Sample Output:
Checking: C:\Users\mikes\Documents\Visual Studio 2017\Projects\CS_Scratch_WindowsFormsApp2\CS_Scratch_WindowsFormsApp2
Checking: C:\Users\mikes\Documents\Visual Studio 2017\Projects\CS_Scratch_WindowsFormsApp2
Checking: C:\Users\mikes\Documents\Visual Studio 2017\Projects
Checking: C:\Users\mikes\Documents\Visual Studio 2017
Checking: C:\Users\mikes\Documents
Checking: C:\Users\mikes
Checking: C:\Users
Checking: C:\
Matches:
C:\Users\mikes\Documents\test.txt
CodePudding user response:
Directory.GetParent(string path)
is the usual way to get a parent directory in .NET. You can use it to "walk up" the filesystem to the root, something like this:
string startPath = @"C:\dir1\dir2\dir3\dir4\file.cs";
string fileName = "test.txt";
DirectoryInfo? currentDirectory = Directory.GetParent(startPath);
while (currentDirectory != null)
{
currentDirectory.FullName.Dump();
string searchPath = Path.Combine(currentDirectory.FullName, fileName);
if (File.Exists(searchPath)
{
// Do something here (like add searchPath to a List<string>)
}
currentDirectory = Directory.GetParent(currentDirectory.FullName);
}