繁体   English   中英

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

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

我有一个字符串文件路径,我想从文件中获取下一个文件夹的名称。

这是我的文件路径:

Test/FilePathNeeded/testing.txt

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

我希望这是有道理的。 请告诉我是否可以。 有人可以帮忙吗?

没有正则表达式,您可以使用:

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

Path.GetDirectoryName将返回Test/FilePathNeeded ,您可以在DirectoryInfo的构造函数中使用它并获取Name

另一个选择是使用Directory.GetParent例如:

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

只需使用:

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

这将返回FilePathNeeded

使用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