-2

I have a path like

string path = @"C:\foo\bar\temp\test\file.txt";

and want to get the foldername of the file - in this case the expected result is "test".

Is there a build in way which is more elegant compared to path.SubString(path.LastIndexOf('/') etc..

Impostor
  • 2,080
  • 22
  • 43
  • 3
    Possible duplicate of [Getting the folder name from a path](https://stackoverflow.com/questions/3736462/getting-the-folder-name-from-a-path) – Nekeniehl Jun 04 '18 at 13:42

4 Answers4

3

You have to use Path.GetDirectoryName (path);

string path = "C:/foo/bar/yourFile.txt";
string folderName = Path.GetFileName(Path.GetDirectoryName(path));

OR

string path = "C:/foo/bar/yourFile.txt";
string folderName = new DirectoryInfo(path).Name;

OR

string path = "C:/foo/bar/yourFile.txt";
string folderName = new FileInfo(path).Directory?.Name;

More info here: https://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx

Nekeniehl
  • 1,633
  • 18
  • 35
2

You can get the name of the file's parent directory by using the DirectoryInfo.Name:

new FileInfo(@"C:\foo\bar\temp\test\file.txt").Directory.Name

This will return 'test' from the example.

Krypt1
  • 1,066
  • 8
  • 14
  • Well there's more or less the same answer there, just they load `DirectoryInfo` using a `DirectoryInfo(System.IO.Path.GetDirectoryName(filename))`, instead of loading through file. – Krypt1 Jun 04 '18 at 14:40
1

Use the static Path class:

Path.GetFileName(Path.GetDirectoryName(path))

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
0

You should use Path.GetDirectoryName() and then take Path.GetFileName().

This example returns what you asked for:

var fileName = @"C:\foo\bar\temp\test\file.txt";
var directoryPath = Path.GetDirectoryName(fileName);
var directoryName = Path.GetFileName(directoryPath); 
Console.WriteLine(directoryName);

Result: test