Problems reading a JSON file in another project
Guys, I'm having trouble reading a certain Json file that is in another project. I did a sample project has that the following structure. Sample.UI.MVC, Sample.Infra.Data, Sample.Domain, Sample.Application. In the Sample.UI.MVC layer I initialize in the Startup.cs file a class that is in the Sample.Infra.Data project, which dynamically generates Seeds in my Database. However, an error is occurring because EF Core is trying to fetch the JSON file inside the Sample.UI.MVC layer and not inside Sample.Infra.Data.
I'm using Asp Net Core 2.2 with VS Code Seed\Seed.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}");
}
}
}
}
But I get the error:
Could not find a part of the path
'D:\App\projects\csharp\asp\core\Sample.UI.MVC\json\UserSeedData.json'.
Code Seed.cs:
View Folder Json:
This isn't a JSON problem, it isn't a C# problem, it isn't a .Net Core 2x problem.
The issue is simply:
Q: If you try reading a file from a relative path, e.g. File.ReadAllText($"json/UserSeedData.json");
, then where is the .exe going to look?
A: It's going to try to look for text file "UserSeedData.json" in directory "json", underneath wherever your .exe is running from.
SUGGESTION:
Define a "JSONDIR" variable setting in your project's appsettings.json, then append that path to the filename when you call File.ReadAllText()
.
EXAMPLE:
https://www.c-sharpcorner.com/article/setting-and-reading-values-from-app-settings-json-in-net-core/
See also:
Sharing appsettings.json configuration files between projects in ASP.NET Core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With