gpt4 book ai didi

c# - 在另一个项目中读取 JSON 文件时出现问题

转载 作者:行者123 更新时间:2023-12-04 15:48:49 28 4
gpt4 key购买 nike

在另一个项目中读取 JSON 文件时出现问题

伙计们,我无法读取另一个项目中的某个 Json 文件。我做了一个示例项目具有以下结构。 Sample.UI.MVC、Sample.Infra.Data、Sample.Domain、Sample.Application。在 Sample.UI.MVC 层中,我在 Startup.cs 文件中初始化了 Sample.Infra.Data 项目中的一个类,该类在我的数据库中动态生成种子。但是,由于 EF Core 试图在 Sample.UI.MVC 层内而不是在 Sample.Infra.Data 内获取 JSON 文件,因此发生了错误。

我正在使用 Asp Net Core 2.2 和 VS Code种子\种子.cs

namespace Sample.Infra.Data.Seed
{
public class Seed
{
private readonly DataContext _context;
private readonly IHostingEnvironment hostingEnvironment;
private readonly UserManager<Usuario> _userManager;

public Seed(DataContext context, IHostingEnvironment hostingEnvironment)
{
_context = context;
hostingEnvironment = hostingEnvironment;
// _userManager = userManager;

}

public void SeedData()
{

try
{
// if (!_userManager.Users.Any())
// {



var userData = File.ReadAllText($"json/UserSeedData.json");
var users = JsonConvert.DeserializeObject<List<Usuario>>(userData);
AddNewType(users);
// }
_context.SaveChanges();

}
catch (Exception ex)
{

Console.WriteLine($"erro: {ex.Message}");
}
}
}
}

但是我得到了错误:

Could not find a part of the path
'D:\App\projects\csharp\asp\core\Sample.UI.MVC\json\UserSeedData.json'.

代码 Seed.cs:

Code Seed.cs

查看文件夹 Json:

View Folder Json

最佳答案

这不是 JSON 问题,不是 C# 问题,也不是 .Net Core 2x 问题。

问题很简单:

问:如果您尝试从相对路径读取文件,例如File.ReadAllText($"json/UserSeedData.json");,那么 .exe 会去哪里找?

答:它将尝试在目录“json”中查找文本文件“UserSeedData.json”,该目录位于您的 .exe 运行所在的位置。

建议:

在项目的 appsettings.json 中定义一个“JSONDIR”变量设置,然后在调用 File.ReadAllText() 时将该路径附加到文件名。

示例:

https://www.c-sharpcorner.com/article/setting-and-reading-values-from-app-settings-json-in-net-core/

另见:

Sharing appsettings.json configuration files between projects in ASP.NET Core

关于c# - 在另一个项目中读取 JSON 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com