本文實例總結了asp.net編程獲取項目根目錄實現方法。分享給大家供大家參考,具體如下:
編寫程序的時候,經常需要用的項目根目錄。自己總結如下
1、取得控制臺應用程序的根目錄方法
方法1、Environment.CurrentDirectory 取得或設置當前工作目錄的完整限定路徑
方法2、AppDomain.CurrentDomain.BaseDirectory 獲取基目錄,它由程序集沖突解決程序用來探測程序集
2、取得Web應用程序的根目錄方法
方法1、HttpRuntime.AppDomainAppPath.ToString();//獲取承載在當前應用程序域中的應用程序的應用程序目錄的物理驅動器路徑。用于App_Data中獲取
方法2、Server.MapPath("") 或者 Server.MapPath("~/");//返回與Web服務器上的指定的虛擬路徑相對的物理文件路徑
方法3、Request.ApplicationPath;//獲取服務器上ASP.NET應用程序的虛擬應用程序根目錄
3、取得WinForm應用程序的根目錄方法
① Environment.CurrentDirectory.ToString();//獲取或設置當前工作目錄的完全限定路徑
② Application.StartupPath.ToString();//獲取啟動了應用程序的可執行文件的路徑,不包括可執行文件的名稱
③ Directory.GetCurrentDirectory();//獲取應用程序的當前工作目錄
④ AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集沖突解決程序用來探測程序集
⑤ AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設置包含該應用程序的目錄的名稱
其中:以下兩個方法可以獲取執行文件名稱
1、Process.GetCurrentProcess().MainModule.FileName;//可獲得當前執行的exe的文件名。
2、Application.ExecutablePath;//獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱
相信很多用asp.net+Access做網站的朋友經常都會有這樣一個需求:就是想在數據庫訪問層類庫中獲取Access數據庫的物理路徑,然后再拼接數據庫連接字符串進行數據庫相關的操作.在網站UI層我們可以有很多種方法獲取一個網站的物理路徑,如:
1. Request.PhysicalApplicationPath
2. Request.MapPath("~/"),但是在數據庫訪問層用這些方法就不行
- using System.Reflection;
- using System.IO; //使用前別忘了引用這兩個命名空間
- /// <summary>
- /// 獲取Access數據庫的物理路徑
- /// </summary>
- /// <returns></returns>
- public static string GetDBPath()
- {
- string str = Assembly.GetExecutingAssembly().Location;
- str = Path.GetDirectoryName(str) + @"/__AssemblyInfo__.ini";
- str = File.ReadAllText(str, System.Text.Encoding.Unicode);
- int index = str.IndexOf("file:///") + 8;
- int length = str.IndexOf("/bin");
- str = str.Substring(index, length - index);
- str = str.Replace('/', '//');
- str += @"/App_Data/DB.mdb";
- return str; //最后返回的就是該數據庫的物理路徑.
- }
新聞熱點
疑難解答
圖片精選