【问题标题】:Read solution data files ASP.Net Core读取解决方案数据文件 ASP.Net Core
【发布时间】:2016-03-07 11:29:17
【问题描述】:

我有一个 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 文件夹是否有效。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc asp.net-core-1.0


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 这在我的机器上对我不起作用,因为它跳过了项目文件夹。即:它需要是“D:\SOLUTION_FOLDER\PROJECT_FOLDER\data\Owners.txt”并尝试从“D:\SOLUTION_FOLDER\data\Owners.txt”中读取
    • 您最好的选择是始终使用IHostingEnvironment
    • 从 .NET Core 3.0 IHostingEnvironment 已过时,应替换为 IWebHostEnvironment
    【解决方案2】:

    您可以在控制器中通过依赖注入获得环境:

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

    【讨论】:

    • 为什么 _env.WebRootPath 会为空?
    • @Corpsekicker...您可能没有注册依赖项
    • 现在 IHostingEnvironment 已过时,应替换为 IWebHostEnvironment
    【解决方案3】:

    在您的控制器中,您可以依赖 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

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

    【讨论】:

    • 感谢您的回复,但我找到了一个更简单的方法,我已发布并将标记为答案。不过谢谢
    • 我给出了一个正确的答案,只是因为它不是您最终选择的确切语法,这不是不接受我的回答恕我直言的好理由。如果我没记错的话,你的答案也只会在 Windows 文件系统上是正确的。
    • 好的,我明白你的观点,你的解决方案将是跨平台的,因此会更好 - 已经给了你答案,谢谢
    • 1.看起来 IApplicationEnvironment 现在已经死了。 IHostingEnvironment 似乎已经取代了它。 2. Path.Combine() 将使这个解决方案更具吸引力:var pathToFile = System.IO.Path.Combine(env.ContentRootPath, "yourfolder", "yourfilename.txt");
    【解决方案4】:

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

    AppDomain.CurrentDomain.BaseDirectory
    

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

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

    【讨论】:

    • 这也与我在使用 dotnet core 的 Raspberry Pi 上工作
    【解决方案5】:

    IApplicationEnvironmentIRuntimeEnvironment 已于 2016 年 4 月 26 日从 announcement on 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)));
    }
    

    【讨论】:

    • 我猜应该是 File.OpenText(pathToFile) 而不仅仅是 OpenText(pathToFile)
    【解决方案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;
        }
    

    这就是调用该方法的方式

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

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2021-10-10
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      相关资源
      最近更新 更多