例如路徑字符串,如何獲得倒數第二個目錄在C#
string path = @"C:\User\Desktop\Drop\images\";
我需要只@"C:\User\Desktop\Drop\
是否有這樣做的任何簡單的方法?
例如路徑字符串,如何獲得倒數第二個目錄在C#
string path = @"C:\User\Desktop\Drop\images\";
我需要只@"C:\User\Desktop\Drop\
是否有這樣做的任何簡單的方法?
您可以使用Path
和Directory
類:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
注意如果路徑不與目錄結束,你會得到不同的結果-separator char \
。然後images
將被理解爲文件名而不是目錄。
您也可以使用此行爲被記錄在案here的Path.GetDirectoryName
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
的後續調用:
因爲返回的路徑不包括DirectorySeparatorChar 或AltDirectorySeparatorChar,通過返回的路徑回到 GetDirectoryName方法將導致一個文件夾的截斷 每個後續cal l在結果字符串上。例如,將 路徑「C:\ Directory \ SubDirectory \ test.txt」放入 GetDirectoryName方法將返回「C:\ Directory \ SubDirectory」。 將該字符串「C:\ Directory \ SubDirectory」傳遞到 GetDirectoryName將導致「C:\ Directory」。
這將返回「C:\ User \ Desktop \ Drop \」例如一切,但最後一個子目錄
string path = @"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(@"\") + 1);
另一種解決辦法,如果你有一個斜線:在頁面的底部
string path = @"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(@"\", splitedPath.Take(splitedPath.Length - 2));
與他的給定的輸入端「\」所以這是行不通的。 –
然後第二個解決方案將與-2 – Blachshma
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string inputText = @"C:\User\Desktop\Drop\images\";
Console.WriteLine(inputText.Substring(0, 21));
}
}
}
輸出:
C:\用戶\桌面\刪除\
有可能是一些簡單的方法來做到這一點使用的文件名或路徑類,但你也可以做這樣的事情解決這個問題(注:未測試):
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
正如我評論GetDirectoryName是自我摺疊它返回路徑沒有tralling斜槓 - 允許獲取下一個目錄。使用Directory.GetParent然後clouse也是有效的。
你可回來了多少級:)
for (int i = 0; i < 3; i++)
path = Directory.GetParent(path).ToString();
+1爲'Directory.GetParent'唯一的解決方案,更安全和更好的方法,而不是字符串操作 – Habib
在給出的例子這Path.GetDirectoryName(Path.GetDirectoryName(路徑))將返回所需的結果,具體取決於任何尾部的斜槓目前它GetDirectoryName將返回當前或父級 – drk
@drk:+有趣的是,編輯我的答案來添加這種方法。 –