本文實(shí)例總結(jié)了asp.net編程獲取項(xiàng)目根目錄實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
編寫程序的時(shí)候,經(jīng)常需要用的項(xiàng)目根目錄。自己總結(jié)如下
1、取得控制臺(tái)應(yīng)用程序的根目錄方法
方法1、Environment.CurrentDirectory 取得或設(shè)置當(dāng)前工作目錄的完整限定路徑
方法2、AppDomain.CurrentDomain.BaseDirectory 獲取基目錄,它由程序集沖突解決程序用來探測(cè)程序集
2、取得Web應(yīng)用程序的根目錄方法
方法1、HttpRuntime.AppDomainAppPath.ToString();//獲取承載在當(dāng)前應(yīng)用程序域中的應(yīng)用程序的應(yīng)用程序目錄的物理驅(qū)動(dòng)器路徑。用于App_Data中獲取
方法2、Server.MapPath("") 或者 Server.MapPath("~/");//返回與Web服務(wù)器上的指定的虛擬路徑相對(duì)的物理文件路徑
方法3、Request.ApplicationPath;//獲取服務(wù)器上ASP.NET應(yīng)用程序的虛擬應(yīng)用程序根目錄
3、取得WinForm應(yīng)用程序的根目錄方法
① Environment.CurrentDirectory.ToString();//獲取或設(shè)置當(dāng)前工作目錄的完全限定路徑
② Application.StartupPath.ToString();//獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,不包括可執(zhí)行文件的名稱
③ Directory.GetCurrentDirectory();//獲取應(yīng)用程序的當(dāng)前工作目錄
④ AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集沖突解決程序用來探測(cè)程序集
⑤ AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設(shè)置包含該應(yīng)用程序的目錄的名稱
其中:以下兩個(gè)方法可以獲取執(zhí)行文件名稱
1、Process.GetCurrentProcess().MainModule.FileName;//可獲得當(dāng)前執(zhí)行的exe的文件名。
2、Application.ExecutablePath;//獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑,包括可執(zhí)行文件的名稱
相信很多用asp.net+Access做網(wǎng)站的朋友經(jīng)常都會(huì)有這樣一個(gè)需求:就是想在數(shù)據(jù)庫(kù)訪問層類庫(kù)中獲取Access數(shù)據(jù)庫(kù)的物理路徑,然后再拼接數(shù)據(jù)庫(kù)連接字符串進(jìn)行數(shù)據(jù)庫(kù)相關(guān)的操作.在網(wǎng)站UI層我們可以有很多種方法獲取一個(gè)網(wǎng)站的物理路徑,如:
1. Request.PhysicalApplicationPath
2. Request.MapPath("~/"),但是在數(shù)據(jù)庫(kù)訪問層用這些方法就不行
- using System.Reflection;
- using System.IO; //使用前別忘了引用這兩個(gè)命名空間
- /// <summary>
- /// 獲取Access數(shù)據(jù)庫(kù)的物理路徑
- /// </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; //最后返回的就是該數(shù)據(jù)庫(kù)的物理路徑.
- }
新聞熱點(diǎn)
疑難解答
圖片精選