2013-02-15 84 views
50

一個選擇是將System.IO.Directory.GetParent()幾次。從執行程序集所在的位置移動幾個文件夾還有更優雅的方式嗎?如何導航幾個文件夾?

我想要做的是找到一個文本文件駐留在應用程序文件夾上方的一個文件夾。但程序集本身位於bin文件夾內,這是應用程序文件夾中的幾個文件夾深處。

+1

多少文件夾? – CR41G14 2013-02-15 16:51:33

+0

說4個文件夾。 – developer747 2013-02-15 16:51:56

+1

通常相對路徑的技巧就像'.. \ .. \ .. \ .. \ Downfolder',但這取決於你想要做什麼...? – DiskJunky 2013-02-15 16:52:16

回答

2

您可以使用.. \路徑上一層,.... \路徑從路徑走兩層。

你也可以使用路徑類。

C# Path class

1

也許如果你想聲明的級別數,並把它變成一個功能,你可以使用函數?

private String GetParents(Int32 noOfLevels, String currentpath) 
{ 
    String path = ""; 
    for(int i=0; i< noOfLevels; i++) 
    { 
     path += @"..\"; 
    } 
    path += currentpath; 
    return path; 
} 

而且你可以這樣調用它:

String path = this.GetParents(4, currentpath); 
+8

這甚至不會編譯... – 2013-12-27 11:30:09

2

下面的方法搜索與應用程序的啓動路徑文件(* .exe文件)開頭的文件。如果在那裏找不到文件,則搜索父文件夾,直到找到文件或到達根文件夾。如果找不到文件,則返回null

public static FileInfo FindApplicationFile(string fileName) 
{ 
    string startPath = Path.Combine(Application.StartupPath, fileName); 
    FileInfo file = new FileInfo(startPath); 
    while (!file.Exists) { 
     if (file.Directory.Parent == null) { 
      return null; 
     } 
     DirectoryInfo parentDir = file.Directory.Parent; 
     file = new FileInfo(Path.Combine(parentDir.FullName, file.Name)); 
    } 
    return file; 
} 

注:Application.StartupPath通常是在WinForms的應用,但它在控制檯應用程序的工作原理爲好;但是,您必須設置對System.Windows.Forms部件的參考。如果您願意,您可以用
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)代替Application.StartupPath

2

這是爲我工作最好的:

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

獲得「正確」的道路是沒有問題的,加上「../」顯然這樣做,但在此之後,給定的字符串不可用,因爲它只會在最後添加'../'。 圍繞它Path.GetFullPath()將給你絕對路徑,使其可用。

94

其他簡單的方法是做到這一點:

string path = @"C:\Folder1\Folder2\Folder3\Folder4"; 
string newPath = Path.GetFullPath(Path.Combine(path, @"..\..\")); 

注意這又向上兩級。其結果將是: newPath = @"C:\Folder1\Folder2\";

1

這可能有助於

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml"; 
if (File.Exists(parentOfStartupPath)) 
{ 
    // file found 
} 
5

如果c:\文件夾1 \文件夾2 \ folder3 \ BIN然後將下面的代碼將返回bin文件夾的路徑基礎文件夾的路徑

string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()); 

即C:\ folder1中\文件夾2 \ folder3

如果你想文件夾2路徑,那麼你可以通過

拿到目錄
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString(); 

那麼你會得到路徑爲c:\文件夾1 \文件夾2 \