路徑 z

最近因為寫到使用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; 
posted on 2014-02-24 17:03  武胜-阿伟  阅读(246)  评论(0编辑  收藏  举报