獲取文件路徑
-------------------------------------------------------------------------
winform獲取文件路徑:
string str1 =Process.GetCurrentProcess().MainModule.FileName;//獲得當前執行的exe的文件名。
string str2=Environment.CurrentDirectory;//獲取和設置當前目錄的完全限定路徑。
string str3=Directory.GetCurrentDirectory();//獲取應用程序的當前工作目錄。
string str4=AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集沖突解決程序用來探測程序集。
string str5=Application.StartupPath;//獲取啟動了應用程序的可執行文件的路徑,不包括可執行文件的名稱。
string str6=Application.ExecutablePath;//獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱。
string str7=AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設置包含該應用程序的目錄的名稱。
“Application.StartupPath”:獲取當前應用程序所在目錄的路徑,最后不包含“\”;
“Application.ExecutablePath ”:獲取當前應用程序文件的路徑,包含文件的名稱;
“AppDomain.CurrentDomain.BaseDirectory”:獲取當前應用程序所在目錄的路徑,最后包含“\”;
“System.Threading.Thread.GetDomain().BaseDirectory”:獲取當前應用程序所在目錄的路徑,最后包含“\”;
“Environment.CurrentDirectory”:獲取當前應用程序的路徑,最后不包含“\”;
“System.IO.Directory.GetCurrentDirectory”:獲取當前應用程序的路徑,最后不包含“\”;
String[] files = System.IO.Directory.GetFiles(path) //返回指定目錄下的文件名
string str = System.IO.Path.GetFileNameWithoutExtension(path);//返回不具有擴展名的指定路徑字符串的文件名
取得控制台應用程序的根目錄方法
方法1、Environment.CurrentDirectory 取得或設置當前工作目錄的完整限定路徑
方法2、AppDomain.CurrentDomain.BaseDirectory 獲取基目錄,它由程序集沖突解決程序用來探測程序集
取得Web應用程序的根目錄方法
方法1、HttpRuntime.AppDomainAppPath.ToString();//獲取承載在當前應用程序域中的應用程序的應用程序目錄的物理驅動器路徑。用於App_Data中獲取 D:\wwwroot\DllTest\
方法2、Server.MapPath("") 或者 Server.MapPath("~/");//返回與Web服務器上的指定的虛擬路徑相對的物理文件路徑 D:\wwwroot\DllTest
方法3、Request.ApplicationPath;//獲取服務器上ASP.NET應用程序的虛擬應用程序根目錄
取得WinForm應用程序的根目錄方法
1、Environment.CurrentDirectory.ToString();//獲取或設置當前工作目錄的完全限定路徑
2、Application.StartupPath.ToString();//獲取啟動了應用程序的可執行文件的路徑,不包括可執行文件的名稱
3、Directory.GetCurrentDirectory();//獲取應用程序的當前工作目錄
4、AppDomain.CurrentDomain.BaseDirectory;//獲取基目錄,它由程序集沖突解決程序用來探測程序集
5、AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//獲取或設置包含該應用程序的目錄的名稱
其中:以下兩個方法可以獲取執行文件名稱
1、Process.GetCurrentProcess().MainModule.FileName;//可獲得當前執行的exe的文件名。
2、Application.ExecutablePath;//獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱
3、System.IO.Path類中有一些獲取路徑的方法,可以在控制台程序或者WinForm中根據相對路徑來獲取絕對路徑
獲取web物理路徑的方法
System.Web.HttpContext.Current.Server.MapPath("~/a/b.config");//獲取指定虛擬路徑下對應的實際物理路徑
讀取項目中某程序集下文件
--------------------------------------------------------------------------
例如:在一個項目中,程序集A,程序集B 在程序集A中要讀取程序集B中的某一模板文件(目錄:B\EmailTempletes\JobsubscritionList.templete)
解決方法如下:
/// <summary> /// 讀取模版 /// </summary> /// <param name="fileName">模版名稱</param> /// <returns>模版內容</returns> private static string ReadEmbedFile(string fileName) { fileName = "B.EmailTempletes.JobsubscritionList.templete";//為方便我直接賦值測試了 Assembly assembly = Assembly.Load("Linkin.Service"); Stream fs = null; StreamReader sr = null; try { fs = assembly.GetManifestResourceStream(fileName); sr = new StreamReader(fs); return sr.ReadToEnd(); } catch { return null; } finally { if (fs != null) fs.Dispose(); if (sr != null) sr.Dispose(); } }