繁体   English   中英

如何在使用IIS运行的Web应用程序中动态找到项目的输出目录?

[英]How do I dynamically locate my project's output directory in a web application run with IIS?

我有一个ASP.NET Web API项目,其中包含许多我想在代码中引用的JSON文件。 我将它们设置为“总是复制”,它们显示在构建的输出目录中。 问题是我不知道如何实际引用输出目录。

我已经看到许多类似问题的答案,这些问题都说要使用System.GetAssembly并使用它来查找文件路径。 但是,这对于Web应用程序根本不起作用,因为GetAssembly或GetProcess方法只是给我IIS或IISExpress目录,而不是项目输出文件夹。

如何在项目输出文件夹中引用项目而不使该进程从该文件夹运行?

编辑:当我按名称加载文件时,得到:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

Additional information: Could not find a part of the path 'C:\Program Files (x86)\IIS Express\myfile.json'.

通过名称引用将在IISExpress文件夹中查找。

相关代码段:

string file = "myjson.json";

var response = Request.CreateResponse(HttpStatusCode.OK);
System.IO.StreamReader myFile = new System.IO.StreamReader(file);
string JSON = myFile.ReadToEnd();
response.Content = new StringContent(JSON);
return response;

如果您没有任何理由将json文件放在输出目录中,请use Content folder ,将json文件放在content文件夹中,然后像这样引用它,

var File = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/myjson.json");

您可以通过名称来引用项目输出目录中的任何资源。 例如,可以按以下方式访问名称为“ File1.txt”的文件:

var fileStream = File.Open("File1.txt", FileMode.Open);

为了在IIS的情况下获得绝对路径,可以采用以下方法:

var absolutePath = HttpContext.Current.Server.MapPath("/");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM