2012-12-18 61 views

回答

8

您可以使用PathDirectory類:

DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path)); 
string parent = parentDir.FullName; 

注意如果路徑不與目錄結束,你會得到不同的結果-separator char \。然後images將被理解爲文件名而不是目錄。

您也可以使用此行爲被記錄在案herePath.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」。

+1

+1爲'Directory.GetParent'唯一的解決方案,更安全和更好的方法,而不是字符串操作 – Habib

+1

在給出的例子這Path.GetDirectoryName(Path.GetDirectoryName(路徑))將返回所需的結果,具體取決於任何尾部的斜槓目前它GetDirectoryName將返回當前或父級 – drk

+0

@drk:+有趣的是,編輯我的答案來添加這種方法。 –

0

這將返回「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)); 
+0

與他的給定的輸入端「\」所以這是行不通的。 –

+0

然後第二個解決方案將與-2 – Blachshma

0
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:\用戶\桌面\刪除\

+0

Eww ...魔術數字('21')? – Yuck

+0

不是,但在這種情況下不是解決方案嗎?我們沒有其他信息包括這一點。 –

+0

在**中,非常具體的情況---但是當編寫好的軟件曾經有過一次針對一個問題的硬編碼? – Yuck

0

有可能是一些簡單的方法來做到這一點使用的文件名或路徑類,但你也可以做這樣的事情解決這個問題(注:未測試):

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... 
1
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也是有效的。

0

你可回來了多少級:)

for (int i = 0; i < 3; i++) 
path = Directory.GetParent(path).ToString();