C # get all parent directories from path to point?

I have a list in WPF that automatically gets FullName from the files listed in the field, and then adds these files to Zip under their specific folder.

For instance:

C: \ ProgramFiles \ Folder1 \ Folder2 \ folder3 \ Folder4 \ file.txt

I need to be able to zip it into my folder to a specific folder, for example, only

\ folder2 \ folder3 \ Folder4 \ file.txt

How can i do this? I tried to get the parent directory, but it only returns the directory where the file is located.

+4
source share
2 answers

You can use the DirectoryInfo object to get the parent chain as much as you need. If you want to get the parent directory at three levels, 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 the way you stop your workaround to meet your needs. Once you have the DirectoryInfo object where you need it, you can do what you need. I assume that you will need the full path or use the Directory object. To get the full path, use the FullName property. If, for example, you need all the files in a directory, you can do the following:

  string[] fileNames = Directory.GetFiles(di.FullName); 
+3
source
  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); } 
0
source

All Articles