C# Console应用程序。当独立运行时和从ASP.NET应用程序中运行时,都可以从磁盘中读取文件。

问题描述 投票:0回答:1

我想知道如何能够 阅文 从两个.NET平台上运行时。

当作为独立运行时

当从主机ASP.NET应用程序中运行时,我知道Server.MapPath命令,但它只在ASP.NET应用程序中工作,我希望从控制台应用程序中加载文件。


我知道Server.MapPath命令,但它只在ASP.NET应用程序上工作,而且我希望文件加载是在控制台应用程序上完成的。


让我们从一个空项目开始,创建两个项目。

首先,一个控制台应用程序。

enter image description here

然后,一个ASP.NET MVC应用程序。

enter image description here

一旦我们有了两个项目,让我们创建一个文本文件。

enter image description here

然后在里面放一些东西。

enter image description here

确保它包含在bin文件夹中。

enter image description here

现在,我们终于可以像这样读取文件内容了。

enter image description here

使用下面的代码。

enter image description here

我们得到了所需的输出。

现在,正如本文开头所说,我希望能够从同一个项目中访问该文件,但从ASP.NET应用程序中调用。

让我们将控制台应用程序添加为TestWebApp的一个项目依赖。

enter image description here

然后像这样调用它的方法。

enter image description here

现在我得到这个错误。

enter image description here


我想知道,当应用程序自己运行时(控制台应用程序)或从主机Web服务(asp.net Web服务器)运行时,我如何继续并能够加载该文件。

c# asp.net file iis
1个回答
1
投票

使用 AppContext.BaseDirectory. 这是运行时检查解析程序集的目录,在你的上下文中,这是最接近输出目录的目录。在你的上下文中,这是最接近输出目录的目录。

现在,它对Console App与Web App的返回内容是有区别的。下面的常用代码可以解决这两个问题。

var appContextBase = AppContext.BaseDirectory;
var filePath = appContextBase.IndexOf("bin", StringComparison.OrdinalIgnoreCase) == -1 ? "bin/Files/File.txt" : "Files/File.txt";
var fileContent = File.ReadAllText(appContextBase + filePath);
Console.WriteLine(fileContent);

对于Console App。AppContext.BaseDirectory 返回类似这样的东西 - "C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MySamples\\bin\\Debug\\"

对于Web App,它的返回是这样的------。"C:\\Users\\user123\\Documents\\Visual Studio 2017\\Projects\\MySamples\\MyWebApp\\"

这也是我在下面添加三元运算符检查的原因。filePath.

© www.soinside.com 2019 - 2024. All rights reserved.