2012-02-01 201 views
1

我的項目中有一個名爲「Images」的文件夾。我想獲取Image文件夾的路徑,以便我可以瀏覽並獲取文件。獲取文件夾相對路徑的方法

我使用下面的一段代碼來滿足我上面的要求,它工作正常。

string basePath = AppDomain.CurrentDomain.BaseDirectory; 
basePath = basePath.Replace("bin", "#"); 
string[] str = basePath.Split('#'); 
basePath = str[0]; 
string path = string.Format(@"{0}{1}", basePath, "Images"); 
string[] fileEntries = Directory.GetFiles(path); 
    foreach (string fileName in fileEntries) 
     listBox.Items.Add(fileName); 

只是想知道像有沒有這樣做的優雅方式?獲取文件夾路徑的最佳方式是什麼?

+0

這是無關的WPF – 2012-02-01 07:51:35

+0

您可以使用['Directory.GetParent'](http://msdn.microsoft.com/en-us/library/system.io .directory.getparent.aspx)來檢索給定目錄的父目錄 – 2012-02-01 08:11:19

回答

4

這就是我通常使用:

string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 

注意它返回一個包含當前執行的代碼的程序集的目錄(我想這是你的主要可執行文件)。

爲了讓生成的路徑的父目錄,你也可以使用

Path.GetDirectoryName(appDirectory); 

我會建議對依賴於你的代碼的Visual Studio項目結構,雖然。考慮將圖像文件夾作爲內容添加到應用程序中,以便它位於與可執行文件相同的目錄中的子目錄中。

1

如果你只是想引用一個與另一個有固定關係的目錄,那麼你可以使用在命令行中使用的相同的語法。

您還應該使用Path類中的方法(例如Path.Combine)而不是所有的字符串操作。

1

你可以簡單的使用Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)