I have a listbox in WPF that automatically gets the FullName of the files listed within the box then will Add those files to a Zip under their specific folder.
For example:
C:\ProgramFiles\Folder1\Folder2\Folder3\Folder4\file.txt
I need to be able to Zip it into its folder up to a specific folder, such as only
\Folder2\Folder3\Folder4\file.txt
How could I do this? I've tried getting the Parent directory, but it only returns the directory the file is in.
private static IEnumerable<DirectoryInfo> GetAllParentDirectories(DirectoryInfo directoryToScan)
{
Stack<DirectoryInfo> ret = new Stack<DirectoryInfo>();
GetAllParentDirectories(directoryToScan, ref ret);
return ret;
}
private static void GetAllParentDirectories(DirectoryInfo directoryToScan, ref Stack<DirectoryInfo> directories)
{
if (directoryToScan == null || directoryToScan.Name == directoryToScan.Root.Name)
return;
directories.Push(directoryToScan);
GetAllParentDirectories(directoryToScan.Parent, ref directories);
}
You can use the DirectoryInfo object to get the parent up the chain as far as you need to. If you want to get a the parent directory three levels up you can do something like this:
DirectoryInfo di = new DirectoryInfo(@"C:\ProgramFiles\Folder1\Folder2\Folder3\Folder4\file.txt");
for(int i = 0; i<3; i++){
di = di.Parent;
}
Obviously, you can change how you stop your traversal to meet your exact need. After you have the DirectoryInfo object where you need it then you can do what you need. I'm assuming you will need either the full path or to use the Directory object. To get the full path use FullName property. If for example you wanted all the files in the directory you could do the following:
string[] fileNames = Directory.GetFiles(di.FullName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With