1. System.IO
命名空間System.IO中存在Directory類,提供了獲取應(yīng)用程序運行當(dāng)前目錄的靜態(tài)方法 System.IO.Directory.GetCurrentDirectory()=>Gets the current working directory of the application, 在.net core中此方法是執(zhí)行dotnet命令所在的目錄.
class Program
{
static void Main(string[] args)
{
var directory = System.IO.Directory.GetCurrentDirectory();
Console.WriteLine(directory);
Console.ReadKey();
}
}
輸出 D:\work\demo\rootpath\ConsoleApp1\ConsoleApp1\bin\Debug\netcoreapp2.2

2. 反射方法: 獲取當(dāng)前執(zhí)行dll所在目錄
Gets the full path or UNC location of the loaded file that contains the manifest => Assembly.GetEntryAssembly().Location
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Assembly.GetEntryAssembly().Location);
Console.ReadKey();
}
}

3. 反射方法: 動態(tài)方式獲取當(dāng)前可執(zhí)行類文件所在目錄
class Program
{
static void Main(string[] args)
{
dynamic type = (new Program()).GetType();
string currentDirectory = Path.GetDirectoryName(type.Assembly.Location);
Console.WriteLine(currentDirectory);
Console.ReadKey();
}
}

4. mvc/api 中獲取相對路徑問題
vs新建.net web application選擇api后可使用注入方式引用IHostingEnvironment對象,可使用此獲取路徑
public class ValuesController : ControllerBase
{
//宿主環(huán)境
private readonly IHostingEnvironment _hostingEnvironment;
public ValuesController(IHostingEnvironment hostingEnvironment)
{
//注入宿主環(huán)境
_hostingEnvironment = hostingEnvironment;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
//wwwroot目錄路徑
//Gets or sets the absolute path to the directory that contains the web-servable application content files
string webRootPath = _hostingEnvironment.WebRootPath;
//應(yīng)用程序所在目錄
//Gets or sets the absolute path to the directory that contains the application content files
string contentRootPath = _hostingEnvironment.ContentRootPath;
return new string[] { webRootPath, contentRootPath };
}
}

- 注意:如果新建項目時選擇的時api模式,
string webRootPath = _hostingEnvironment.WebRootPath;//為null,因為默認(rèn)沒有wwwroot目錄,且沒有啟用靜態(tài)文件服務(wù)需要開啟服務(wù)
在Startup.cs的Configure中添加app.UseStaticFiles();,并且在應(yīng)用根目錄中添加文件夾命名為wwwroot即可
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
//開啟靜態(tài)文件服務(wù) 默認(rèn)為wwwroot路徑
app.UseStaticFiles();
}
5. 修改mvc/api中wwwroot靜態(tài)文件夾的路徑
首先在wwwroot文件下放上a.txt文件內(nèi)容為hello,world.
運行后訪問http://localhost:58397/a.txt顯示為hello,world.,說明默認(rèn)靜態(tài)文件起作用,如果不想在默認(rèn)的應(yīng)用程序下放wwwroot或者靜態(tài)文件路徑已經(jīng)指向了固定位置,則需要使用StaticFileOptions修改默認(rèn)靜態(tài)文件夾的路徑
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
var staticFile = new StaticFileOptions();
staticFile.FileProvider = new PhysicalFileProvider(@"c:\data\");//指定靜態(tài)文件目錄
//開啟靜態(tài)文件服務(wù) 默認(rèn)為wwwroot路徑
app.UseStaticFiles(staticFile);
}

訪問成功!
6. 顯示靜態(tài)文件路徑下的所有文件
另外一個問題是,如何顯示靜態(tài)文件夾里的所有文件, 可以使用UseDirectoryBrowser
首先需要在ConfigureServices中注冊目錄瀏覽器,然后在Configure中使用
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
var staticFilePath = @"c:\data\";//指定靜態(tài)文件目錄
var dir = new DirectoryBrowserOptions();
dir.FileProvider = new PhysicalFileProvider(staticFilePath);
app.UseDirectoryBrowser(dir);
var staticFile = new StaticFileOptions();
staticFile.FileProvider = new PhysicalFileProvider(staticFilePath);
//開啟靜態(tài)文件服務(wù) 默認(rèn)為wwwroot路徑
app.UseStaticFiles(staticFile);
}

瀏覽器默認(rèn)支持瀏覽的格式是有限的,并且iis或其他service提供的mime也是有限的,瀏覽器打開不支持的文件類型的時候會報404錯誤,所以就需要增加配置iis的mime類型,當(dāng)遇到不識別的MIME類型的時候默認(rèn)為下載,或者可以在應(yīng)用程序中指定部分類型為可識別類型,如.log,.conf等為文本文件格式
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
var staticFilePath = @"c:\data\";//指定靜態(tài)文件目錄
var dir = new DirectoryBrowserOptions();
dir.FileProvider = new PhysicalFileProvider(staticFilePath);
app.UseDirectoryBrowser(dir);
var staticFile = new StaticFileOptions();
staticFile.FileProvider = new PhysicalFileProvider(staticFilePath);
staticFile.ServeUnknownFileTypes = true;
staticFile.DefaultContentType = "application/x-msdownload";//設(shè)置默認(rèn)MIME,此處為下載
var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
fileExtensionContentTypeProvider.Mappings.Add(".log", "text/plain");//設(shè)置特定類型的MIME
fileExtensionContentTypeProvider.Mappings.Add(".conf", "text/plain");
staticFile.ContentTypeProvider = fileExtensionContentTypeProvider;
//開啟靜態(tài)文件服務(wù) 默認(rèn)為wwwroot路徑
app.UseStaticFiles(staticFile);
}
啟用靜態(tài)文件服務(wù)的簡寫形式
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseFileServer(new FileServerOptions()
{
//此種方式貌似不支持指定mime類型,望指出如何實現(xiàn)
FileProvider = new PhysicalFileProvider(@"c:\data\"),
EnableDirectoryBrowsing = true,
});
}
博客文章可以轉(zhuǎn)載,但不可以聲明為原創(chuàng).