读取解决方案数据文件ASP.Net Core

Mar*_*arn 32 c# asp.net-core-mvc asp.net-core asp.net-core-1.0

我有一个ASP.NET Core(1.0-rc1-final)MVC解决方案,我希望在项目中存储一个简单的文本文件,其中包含我在控制器中读入字符串数组的字符串列表.

我应该将这个文件存储在我的项目中,如何在控制器中读取这些文件?

在ASP.net 4.x我已经使用过该app_data文件夹并完成了类似的操作

string path = Server.MapPath("~/App_Data/File.txt");
string[] lines = System.IO.File.ReadAllLines(path);
Run Code Online (Sandbox Code Playgroud)

Server.MapPath在ASP.Net Core 1中似乎没有效果,我也不确定该app_data文件夹是否存在.

Mar*_*arn 27

我找到了一个简单的解决方案.

首先,您可以在解决方案的任何位置创建一个文件夹,您不必遵守.net 4.x中的"app_data"等约定.

在我的场景中,我在项目的根目录下创建了一个名为"data"的文件夹,我将txt文件放在那里并使用此代码将内容读取到字符串数组

var owners = System.IO.File.ReadAllLines(@"..\data\Owners.txt");

  • 从 .NET Core 3.0 开始,IHostingEnvironment 已过时,应由 IWebHostEnvironment 替换 (5认同)
  • 这在我的机器上不起作用,因为它会跳过项目文件夹。即:它需要是“D:\SOLUTION_FOLDER\PROJECT_FOLDER\data\Owners.txt”,并尝试从“D:\SOLUTION_FOLDER\data\Owners.txt”读取 (2认同)
  • 最好的选择是始终使用[IHostingEnvironment](https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.hosting.ihostingenvironment?view=aspnetcore-2.1) (2认同)

Joe*_*tte 12

在您的控制器中,您可以依赖IApplicationEnvironment并将其注入构造函数,然后您可以使用它来建立文件的路径,以便您的文件可以存在于项目中的文件夹中.在下面的示例中,"env"是IApplicationEnvironment的实例

using Microsoft.Extensions.PlatformAbstractions;

var pathToFile = env.ApplicationBasePath 
   + Path.DirectorySeparatorChar.ToString() 
   + "yourfolder"
   + Path.DirectorySeparatorChar.ToString() 
   + "yourfilename.txt";

string fileContent;

using (StreamReader reader = File.OpenText(pathToFile))
{
    fileContent = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

ApplicationBasePath表示applicationRootFolder

请注意,还存在IHostingEnvironment,它具有熟悉的.MapPath方法,但它适用于存储在wwwroot文件夹下的内容.您应该只存储要通过http请求提供的wwwroot文件夹下的内容,因此最好将字符串列表保存在不同的文件夹中.

  • 1. 看起来 IApplicationEnvironment 现在已经死了。IHostingEnvironment 似乎已经取代了它。2. Path.Combine() 将使这个解决方案更具吸引力:`var pathToFile = System.IO.Path.Combine(env.ContentRootPath, "yourfolder", "yourfilename.txt");` (2认同)

Pie*_*pen 11

您可以在控制器中获得具有依赖注入的环境:

using Microsoft.AspNetCore.Hosting;
....

public class HomeController: Controller
{
   private IHostingEnvironment _env;

   public HomeController(IHostingEnvironment env)
   {
   _env = env;
   }   
...
Run Code Online (Sandbox Code Playgroud)

然后,您可以在操作中获取wwwroot位置:_env.WebRootPath

var owners =   System.IO.File.ReadAllLines(System.IO.Path.Combine(_env.WebRootPath,"File.txt"));
Run Code Online (Sandbox Code Playgroud)

  • 现在 IHostingEnvironment 已过时,应由 IWebHostEnvironment 取代 (5认同)

zdu*_*dub 11

这在本地和 IIS 上一直对我有用。

AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)

要访问您的文件,您只需执行以下操作:

import System.IO
...
var owners = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File.txt"))
Run Code Online (Sandbox Code Playgroud)


sea*_*ght 7

IApplicationEnvironment并于2016 年4月26 日在github发布时IRuntimeEnvironment已被删除。

我用这个替换了@JoeAudette的代码

private readonly string pathToFile;

public UsersController(IHostingEnvironment env)
{
    pathToFile = env.ContentRootPath
       + Path.DirectorySeparatorChar.ToString()
       + "Data"
       + Path.DirectorySeparatorChar.ToString()
       + "users.json";
}
Run Code Online (Sandbox Code Playgroud)

我的.json文件所在的位置src/WebApplication/Data/users.json

然后我像这样读取/解析此数据

private async Task<IEnumerable<User>> GetDataSet()
{
    string source = "";

    using (StreamReader SourceReader = OpenText(pathToFile))
    {
        source = await SourceReader.ReadToEndAsync();
    }

    return await Task.FromResult(JsonConvert.DeserializeObject<IEnumerable<User>>(source)));
}
Run Code Online (Sandbox Code Playgroud)


小智 6

这种方法在本地和 Azure 环境中对我有用。它取自上面乔的回答

public static string ReadFile(string FileName)
    {
        try
        {
            using (StreamReader reader = File.OpenText(FileName))
            {
                string fileContent = reader.ReadToEnd();
                if (fileContent != null && fileContent != "")
                {
                    return fileContent;
                }
            }
        }
        catch (Exception ex)
        {
            //Log
            throw ex;
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

这就是调用该方法的方式

string emailContent = ReadFile("./wwwroot/EmailTemplates/UpdateDetails.html");
Run Code Online (Sandbox Code Playgroud)