簡體   English   中英

讀取解決方案數據文件 ASP.Net Core

[英]Read solution data files ASP.Net Core

我有一個 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);

但是Server.MapPath在 ASP.Net Core 1 中似乎無效,我不確定app_data文件夾是否也是如此。

我找到了一個簡單的解決方案。

首先,您可以在解決方案的任何位置創建一個文件夾,您不必遵守 .net 4.x 中的“app_data”等約定。

在我的場景中,我在項目的根目錄創建了一個名為“data”的文件夾,將我的 txt 文件放在那里,並使用此代碼將內容讀取到字符串數組中

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

您可以在控制器中使用依賴注入獲得環境:

using Microsoft.AspNetCore.Hosting;
....

public class HomeController: Controller
{
   private IHostingEnvironment _env;

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

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

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

在您的控制器中,您可以依賴 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 代表 applicationRootFolder

請注意,還存在具有熟悉的 .MapPath 方法的 IHostingEnvironment,但它用於存儲在 wwwroot 文件夾下的內容。 您應該只在 wwwroot 文件夾下存儲您想要通過 http 請求提供服務的內容,因此最好將您的字符串列表保存在不同的文件夾中。

這在本地和 IIS 上一直對我有用。

AppDomain.CurrentDomain.BaseDirectory

要訪問您的文件,您只需執行以下操作:

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

IApplicationEnvironmentIRuntimeEnvironment已於2016 年 4月 26日在 github發布公告刪除。

我用這個替換了@JoeAudette 的代碼

private readonly string pathToFile;

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

我的.json文件位於src/WebApplication/Data/users.json

然后我像這樣讀取/解析這些數據

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

這種方法在本地和 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;
    }

這就是調用該方法的方式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM