简体   繁体   中英

Regex to get whatever the parent directory of my file is in string file path

I have a string file path and I am looking to get the name of the folder that is next up from the file.

Here is my file path:

Test/FilePathNeeded/testing.txt

I am sure there is a way to get FilePathNeeded from the file path above with regex, I just am not sure how it would be done. My thought is that the amount of directories that testing.txt is in should not matter, but the folder needed would always be one up from the file.

I hope this makes sense. Please let me know if it doesn't. Would anyone be able to help?

Without Regex, You can use:

string directory = new DirectoryInfo(
                               Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
                                    ).Name;

Path.GetDirectoryName will return Test/FilePathNeeded that you can use in the constructor of DirectoryInfo and get Name .

Another option is to use Directory.GetParent like:

var directory  = Directory.GetParent("Test/FilePathNeeded/testing.txt").Name;

Simply use:

var dir = new FileInfo("Test/FilePathNeeded/testing.txt").Directory.Name;

This will return FilePathNeeded

Use the FileInfo class:

  var fileInfo = new FileInfo(@"Test/FilePathNeeded/testing.txt");
  var directoryInfo = fileInfo.Directory;
  var parentDirectoryName = directoryInfo.Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM