-1

I'm using

FolderBrowserDialog fbd = new FolderBrowserDialog();
string[] filePaths = Directory.GetFiles(fbd.SelectedPath, "*",SearchOption.AllDirectories);

filePaths are the following:

C:\Users\Stef\Desktop\bgdm_v2015\bgdm.dll
C:\Users\Stef\Desktop\bgdm_v2015\something.txt
C:\Users\Stef\Desktop\bgdm_v2015\folder2\file.txt
C:\Users\Stef\Desktop\bgdm_v2015\folder2\file2.txt
C:\Users\Stef\Desktop\bgdm_v2015\folder2\folder3\file.txt

Is there any function to get the parent directory to the files? Like only

bgdm_v2015
bgdm_v2015
bgdm_v2015
folder2
folder2
folder3
Stefan
  • 83
  • 1
  • 6
  • 20

3 Answers3

5

Path.GetDirectoryName returns the full path of the parent, and Path.GetFileName returns the last segment of the path (which can actually be a directory, not necessarily a file). So you can do this:

string parentDirectoryName = Path.GetFileName(Path.GetDirectoryName(fullPath));
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

There is more than one way to achieve your task.

solution 1:

var result = Path.GetFileName(Path.GetDirectoryName("Enter Path here"));

solution 2:

FileInfo info = new FileInfo("Enter Path here");   
String getDirectoryName = info.Directory.Name;
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You can use FileInfo to do it.

var fileInfo = new FileInfo(fileWithPath);
var parentName = fileInfo.Directory.Name;
itsme86
  • 19,266
  • 4
  • 41
  • 57