[英]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.