C# 實現(xiàn)在當(dāng)前目錄基礎(chǔ)上找到上一層目錄
更新時間:2021年01月14日 10:32:46 作者:creay_king
這篇文章主要介紹了C# 實現(xiàn)在當(dāng)前目錄基礎(chǔ)上找到上一層目錄,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
其實很簡單也很無腦,但卻很實用,就是使用拆字符串的方法:
/// <summary> /// 獲得項目的根路徑 /// </summary> /// <returns></returns> public string GetProjectRootPath() { string rootPath = ""; string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; // F:\project\WPF\AstroATE-PDR\04. 程序\01. 源代碼\AstroATE\AstroATE\bin\Debug // 向上回退三級,得到需要的目錄 rootPath = BaseDirectoryPath.Substring(0, BaseDirectoryPath.LastIndexOf("\\")); // 第一個\是轉(zhuǎn)義符,所以要寫兩個 rootPath = rootPath.Substring(0, rootPath.LastIndexOf(@"\")); // 或者寫成這種格式 rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\\")); // @"F:\project\WPF\AstroATE-PDR\04. 程序\01. 源代碼\AstroATE\AstroATE return rootPath; }
調(diào)用該函數(shù):
string str = GetProjectRootPath() + @"\data\幫助文檔.pdf"; //找到需要找的文件
好了,這樣就解決了。
補充:C# 如何獲取可執(zhí)行文件路徑的上上級目錄
第一種:
DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}..\..\", Application.StartupPath)); di.FullName
..\有幾個就是往回退幾層
第二種:
DirectoryInfo info = new DirectoryInfo(Application.StartupPath); String path = info.Parent.Parent.FullName;
第三種:
string WantedPath = Application.StartupPath.Substring(0,Application.StartupPath.LastIndexOf(@"\"));
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
C# MeasureString測量字符串函數(shù)的使用方法
這篇文章主要介紹了C# MeasureString測量字符串函數(shù)的使用方法,需要的朋友可以參考下2014-10-10Unity 按鈕事件封裝操作(EventTriggerListener)
這篇文章主要介紹了Unity 按鈕事件封裝操作(EventTriggerListener),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04