.net Core 獲取當前程序路徑


1.先創建一個類:

 public static class MyServiceProvider
    {
        public static IServiceProvider ServiceProvider
        {
            get; set;
        }
    }

2.Startup.cs中Configure方法中添加    MyServiceProvider.ServiceProvider = app.ApplicationServices;     

 

 

 

 

3.在需要用到程序路徑的地方,引用

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

string path = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().ContentRootPath;  //.NET Core 3.1,IHostingEnvironment 要改為IHostEnvironment

 

效果如下:

 

 

獲取了路徑:D:\\Project\\MyWebsite\\UI

 

4.如果需要獲取UI下的wwwroot路徑方法得改一下,為

    static string path = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().WebRootPath;  //.NET Core 3.1,IHostingEnvironment 要改為IHostEnvironment

 


免責聲明!

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



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