[WinForm|WPF|C#] 取得專案路徑與移動至上層目錄-使用DirectoryInfo

  • 18722
  • 0
  • C#
  • 2013-12-26

最近因為寫到使用FileDialog開檔讀檔的關係,所以在打開時,會常常需要移動到資料夾所在路徑,因此就在想要如何才能指定開啟FileDialog 能夠就指定在想要的資料夾上,並且移動整個專案時,不會因為絕對路徑的關係發生錯誤,以下開始。

前言

 


 

最近因為寫到使用FileDialog開檔讀檔的關係,所以在打開時,會常常需要移動到資料夾所在路徑,因此就在想要如何才能指定開啟FileDialog 能夠就指定在想要的資料夾上,並且移動整個專案時,不會因為絕對路徑的關係發生錯誤,以下開始。

此篇適用WinForm

 

如何取得專案所在的資料夾路徑

 


 

方法有很多種,這邊介紹WinForm與Console模式下可是用的方式(有興趣可以去看參考資料的來源):

 

1.抓取 WinForm 應用程式所在的目錄,傳應用程式設定執行檔輸出目錄的路徑

string path = System.Windows.Forms.Application.StartupPath

 

2.抓取 Console 與WPF應用程式所在的目錄可使用的方式

string path = System.AppDomain.CurrentDomain.BaseDirectory

3.透過Directory的GetCurrentDirectory (WinForm、WPF)取得目前應用程式工作目錄

string path = Directory.GetCurrentDirectory()

 

如何移動目前的路徑至上層

 


 

1.使用DirectoryInfo類別初始化,並傳入專案執行檔所在目錄

DirectoryInfo dir = new DirectoryInfo(System.Windows.Forms.Application.StartupPath);
 

2.移動至上層目錄

string s = dir.Parent; 
 

3.若想要取得絕對路徑

string s = dir.Parent.FullName; 
 

4.搭配使用OpenFileDialog

OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = dir.Parent.Parent.FullName + @"\想要移動的其他目錄"; //指定FileDialog開啟時所在的目錄
dlg.RestoreDirectory = true; 

 

 

參考資料


[C#][ASP.NET] 取得目前執行程式的目錄

C# WINFORM 取得執行程式所在的路徑方法

C# 將工作目錄移至上層目錄

What is the WPF equivalent to “System.Windows.Forms.Application.X” for obtaining startup path, app data path, etc.?

 


 

文章中的敘述如有觀念不正確錯誤的部分,歡迎告知指正 謝謝 =)

另外要轉載請附上出處 感謝