C#獲取根目錄的方法總結

撈月亮的猴子發表於2019-01-04

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("/");
        }
     }

補充:WebForm /Mvc /WebApi專案的根目錄為配置檔案Web.config所在的目錄。

 

相關文章