简体   繁体   English

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

[英]Read solution data files ASP.Net Core

I have an ASP.NET Core (1.0-rc1-final) MVC solution and I wish to store a simple text file within the project which contain a list of strings which I read into a string array in my controller.我有一个 ASP.NET Core (1.0-rc1-final) MVC 解决方案,我希望在项目中存储一个简单的文本文件,其中包含我读入控制器中的字符串数组的字符串列表。

Where should I store this file in my project and how do I read those files in my controllers?我应该将此文件存储在我的项目中的什么位置,以及如何在我的控制器中读取这些文件?

In ASP.net 4.x I'd have used the app_data folder and done something like this在 ASP.net 4.x 中,我会使用app_data文件夹并完成类似的操作

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

But Server.MapPath does not seem to be valid in ASP.Net Core 1 and I'm not sure that the app_data folder is either.但是Server.MapPath在 ASP.Net Core 1 中似乎无效,我不确定app_data文件夹是否也是如此。

I found a simple solution to this.我找到了一个简单的解决方案。

Firstly, you can create a folder anywhere in your solution, you do not have to stick to the conventions like 'app_data' from .net 4.x.首先,您可以在解决方案的任何位置创建一个文件夹,您不必遵守 .net 4.x 中的“app_data”等约定。

In my scenario, I created a folder called 'data' at the root of my project, I put my txt file in there and used this code to read the contents to a string array在我的场景中,我在项目的根目录创建了一个名为“data”的文件夹,将我的 txt 文件放在那里,并使用此代码将内容读取到字符串数组中

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

You can get the enviroment with Dependency Injection in your controller:您可以在控制器中使用依赖注入获得环境:

using Microsoft.AspNetCore.Hosting;
....

public class HomeController: Controller
{
   private IHostingEnvironment _env;

   public HomeController(IHostingEnvironment env)
   {
   _env = env;
   }   
...

Then you can get the wwwroot location in your actions: _env.WebRootPath然后您可以在您的操作中获取 wwwroot 位置:_env.WebRootPath

var owners =   System.IO.File.ReadAllLines(System.IO.Path.Combine(_env.WebRootPath,"File.txt"));

in your controller you could take a dependency on IApplicationEnvironment and have it injected into the constructor then you can use it to establish the path to your file so your file can live in a folder within the project.在您的控制器中,您可以依赖 IApplicationEnvironment 并将其注入到构造函数中,然后您可以使用它来建立文件的路径,以便您的文件可以存在于项目中的文件夹中。 In the example below "env" is the instance of 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();
}

ApplicationBasePath represents the applicationRootFolder ApplicationBasePath 代表 applicationRootFolder

note that there also exists IHostingEnvironment which has the familiar .MapPath method, but it is for things stored below the wwwroot folder.请注意,还存在具有熟悉的 .MapPath 方法的 IHostingEnvironment,但它用于存储在 wwwroot 文件夹下的内容。 You should only store things below the wwwroot folder that you want to serve with http requests so it is better to keep your list of strings in a different folder.您应该只在 wwwroot 文件夹下存储您想要通过 http 请求提供服务的内容,因此最好将您的字符串列表保存在不同的文件夹中。

This has always worked for me locally and on IIS.这在本地和 IIS 上一直对我有用。

AppDomain.CurrentDomain.BaseDirectory

To access your file, you could simply do the following:要访问您的文件,您只需执行以下操作:

import System.IO
...
var owners = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File.txt"))

IApplicationEnvironment and IRuntimeEnvironment have been removed as of an announcement on github on 2016/04/26. IApplicationEnvironmentIRuntimeEnvironment已于2016 年 4月 26日在 github发布公告删除。

I replaced @JoeAudette's code with this我用这个替换了@JoeAudette 的代码

private readonly string pathToFile;

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

Where my .json file is located at src/WebApplication/Data/users.json我的.json文件位于src/WebApplication/Data/users.json

I then read/parse this data like so然后我像这样读取/解析这些数据

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

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

    return await Task.FromResult(JsonConvert.DeserializeObject<IEnumerable<User>>(source)));
}

This method worked for me locally and on Azure environment.这种方法在本地和 Azure 环境中对我有用。 It is taken from Joe's answer above它取自上面乔的回答

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;
    }

And this is how invoked that method这就是调用该方法的方式

string emailContent = ReadFile("./wwwroot/EmailTemplates/UpdateDetails.html");

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

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