2013年2月6日 星期三

[C#] 取得專案路徑與移動至上層目錄

前言

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

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

方法有很多種,這邊介紹WinForm與Console模式下可是用的方式(有興趣可以去看參考資料的來源):
  • 抓取 WinForm 應用程式所在的目錄,傳應用程式設定執行檔輸出目錄的路徑
  •   
    string path = System.Windows.Forms.Application.StartupPath
         
  • 抓取 Console 應用程式所在的目錄可使用的方式
  • string path = System.AppDomain.CurrentDomain.BaseDirectory
         

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

  • 使用DirectoryInfo類別初始化,並傳入專案執行檔所在目錄
  •   
    DirectoryInfo dir = new DirectoryInfo(System.Windows.Forms.Application.StartupPath);
         
  • 移動至上層目錄
  • string s = dir.Parent; 
         
  • 若想要取得絕對路徑
  • string s = dir.Parent.FullName; 
         
  • 搭配使用OpenFileDialog
  • OpenFileDialog dlg = new OpenFileDialog();
    dlg.InitialDirectory = dir.Parent.Parent.FullName + @"\想要移動的其他目錄"; //指定FileDialog開啟時所在的目錄
    dlg.RestoreDirectory = true; 
    

    參考資料

  • [C#][ASP.NET] 取得目前執行程式的目錄
  • C# WINFORM 取得執行程式所在的路徑方法
  • C# 將工作目錄移至上層目錄
  • 沒有留言:

    張貼留言