c# 獲取當前程序運行根目錄


//獲取絕對路徑,調用如

string fileName = string.Format("~/RuleConfigFiles/Campaign_{0}.JSON", CampaignID);
var localFile = Utilities.MapPath(fileName);

 

static public string MapPath(string url)   

{    

if (HttpContext.Current != null)     

  return HttpContext.Current.Server.MapPath(url);

return System.Web.Hosting.HostingEnvironment.MapPath(url);   

}

 

 

 

// 獲取程序的基目錄。  

1.System.AppDomain.CurrentDomain.BaseDirectory

// 獲取模塊的完整路徑。

2.System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName


// 獲取和設置當前目錄(該進程從中啟動的目錄)的完全限定目錄。

3.System.Environment.CurrentDirectory


// 獲取應用程序的當前工作目錄。

4.System.IO.Directory.GetCurrentDirectory()

// 獲取和設置包括該應用程序的目錄的名稱。

5.System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

// 獲取啟動了應用程序的可執行文件的路徑。

6.System.Windows.Forms.Application.StartupPath


// 獲取啟動了應用程序的可執行文件的路徑及文件名

7.System.Windows.Forms.Application.ExecutablePath

 

 

 

1、取得控制台應用程序的根目錄方法

方法1、Environment.CurrentDirectory 取得或設置當前工作目錄的完整限定路徑
方法2、AppDomain.CurrentDomain.BaseDirectory 獲取基目錄,它由程序集沖突解決程序用來探測程序集

2、取得Web應用程序的根目錄方法

方法1、HttpRuntime.AppDomainAppPath.ToString();//獲取承載在當前應用程序域中的應用程序的應用程序目錄的物理驅動器路徑。

如string xmlPath = System.Web.HttpRuntime.AppDomainAppPath + "\\ConfigFiles\\BaseConfig.xml";


方法2、Server.MapPath("") 或者 Server.MapPath("~/");//返回與Web服務器上的指定的虛擬路徑相對的物理文件路徑
方法3、Request.ApplicationPath;//獲取服務器上ASP.NET應用程序的虛擬應用程序根目錄

3、取得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;//獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM