Read files from project Folder (Directory) in ASP.Net Core

rakibxl
 
on Mar 23, 2021 02:54 AM
10507 Views

How to read file from project folder in asp.net core.

I am importing country data using JSON file but that JSON file, I am reading from the computer c drive temp folder. But now I want that to read the JSON file from the project folder.

private void SeedData(EntityTypeBuilder<Country> builder)
{
    using (StreamReader r = new StreamReader(@"C:\temp\CountryImport.json"))
    {
        string json = r.ReadToEnd();
        List<Country> countries = JsonConvert.DeserializeObject<List<Country>>(json);
        builder.HasData(countries);
    }
 }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 23, 2021 02:57 AM
on Mar 23, 2021 03:57 AM

Hi rakibxl,

Refer below code.

private void SeedData(EntityTypeBuilder<Country> builder)
{
    using (StreamReader r = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Json/CountryImport.json")))
    {
        string json = r.ReadToEnd();
 
        List<Country> countries = JsonConvert.DeserializeObject<List<Country>>(json);
 
        builder.HasData(countries); 
    }
}

 

rakibxl
 
on Mar 23, 2021 04:01 AM

The type or namespace name 'HttpContext' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

This is actually in my dot net core project 

dharmendr
 
on Mar 23, 2021 04:25 AM
rakibxl
 
on Mar 25, 2021 11:11 AM

Below code solved my issue

private void SeedData(EntityTypeBuilder<Country> builder)
{
    string currentDirectory = Directory.GetCurrentDirectory();
    string path = "Json";
    string fullPath = Path.Combine(currentDirectory, path, "CountryImport.json");
    using (StreamReader r = new StreamReader(fullPath))
    {
        string json = r.ReadToEnd();
        List<Country> countries = JsonConvert.DeserializeObject<List<Country>>(json);
        builder.HasData(countries);
    }
}