简体   繁体   English

正则表达式获取我文件的父目录在字符串文件路径中的任何内容

[英]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. 我敢肯定有一种方法可以使用正则表达式从上面的文件路径中获取FilePathNeeded ,但我不确定该怎么做。 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. 我的想法是, testing.txt所在的目录数量无关紧要,但是所需的文件夹始终是文件中的一个。

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 . Path.GetDirectoryName将返回Test/FilePathNeeded ,您可以在DirectoryInfo的构造函数中使用它并获取Name

Another option is to use Directory.GetParent like: 另一个选择是使用Directory.GetParent例如:

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 这将返回FilePathNeeded

Use the FileInfo class: 使用FileInfo类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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