1.控制台应用程序 static void Main(string[] args) { //1.Environment.CurrentDirectory Console.WriteLine(Environment.CurrentDirectory); //2.AppDomain.CurrentDomain.BaseDirectory Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
1.控制台应用程序
static void Main(string[] args) { //1.Environment.CurrentDirectory Console.WriteLine(Environment.CurrentDirectory); //2.AppDomain.CurrentDomain.BaseDirectory Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); //3.项目的目录 Console.WriteLine(Path.GetFullPath("../../")); Console.ReadKey(); }
运行结果:
2.winform应用程序
private void Form1_Load(object sender, EventArgs e) { //1.Environment.CurrentDirectory txtBox1.Text = Environment.CurrentDirectory; //2.Application.StartupPath txtBox2.Text = Application.StartupPath; //3.Directory.GetCurrentDirectory() txtBox3.Text = Directory.GetCurrentDirectory(); //4.AppDomain.CurrentDomain.BaseDirectory txtBox4.Text = AppDomain.CurrentDomain.BaseDirectory; }
运行结果:
3.MVC和WebForm项目
通过Server.MapPath("/")获取根目录
//WebForm <h1><%=Server.MapPath("/") %></h1> //Mvc <h1>@Server.MapPath("/")</h1>
4.WebApi项目
public class ValuesController : ApiController { //api/values public string Get() { return System.Web.Hosting.HostingEnvironment.MapPath("/"); } }
WebApi Core的根目录获取:HttpRuntime.AppDomainAppPath
补充:WebForm /Mvc /WebApi项目的根目录为配置文件Web.config所在的目录。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。