C# Regex以获取我的文件的父目录在字符串文件路径中的任何内容

C# Regex以获取我的文件的父目录在字符串文件路径中的任何内容,c#,regex,C#,Regex,我有一个字符串文件路径,我希望从文件中获得下一个文件夹的名称 这是我的文件路径: Test/FilePathNeeded/testing.txt 我确信有一种方法可以通过regex从上面的文件路径中获取所需的文件路径,我只是不确定该如何实现。我的想法是testing.txt所在的目录数量应该无关紧要,但所需的文件夹总是在文件的上方 我希望这是有道理的。如果没有,请告诉我。有人能帮忙吗 没有Regex,您可以使用: string directory = new DirectoryInfo(

我有一个字符串文件路径,我希望从文件中获得下一个文件夹的名称

这是我的文件路径:

Test/FilePathNeeded/testing.txt
我确信有一种方法可以通过regex从上面的文件路径中获取所需的文件路径,我只是不确定该如何实现。我的想法是testing.txt所在的目录数量应该无关紧要,但所需的文件夹总是在文件的上方


我希望这是有道理的。如果没有,请告诉我。有人能帮忙吗

没有Regex,您可以使用:

string directory = new DirectoryInfo(
                               Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
                                    ).Name;
Path.GetDirectoryName将返回您可以在DirectoryInfo和get Name的构造函数中使用的Test/FilePathNeeded

另一个选项是使用Directory.GetParent,如:


没有Regex,您可以使用:

string directory = new DirectoryInfo(
                               Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
                                    ).Name;
Path.GetDirectoryName将返回您可以在DirectoryInfo和get Name的构造函数中使用的Test/FilePathNeeded

另一个选项是使用Directory.GetParent,如:


使用FileInfo类:

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

使用FileInfo类:

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

var dir = new FileInfo("Test/FilePathNeeded/testing.txt").Directory.Name;
这将返回所需的文件路径

只需使用:

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

这将返回FilePathNeeded

这是您使用正则表达式的一个要求吗?@TomFenech-我想不必,我只是在寻找最有效的方法。var dir=Path.GetDirectoryNameTest/FilePathNeeded/testing.txt@EZI,这将返回Test/FilePathNeededIs这是您使用regex的一个要求吗?@TomFenech-我想不必,我只是在寻找最有效的方法。var dir=Path.GetDirectoryNameTest/FilePathNeeded/testing.txt@EZI,这将返回Test/FilePathNeeded