How to read a text file on the INFRA.DATA layer of an Asp.net Core - C#

Asked

Viewed 133 times

2

In the Infra.Data layer, I configured the properties of a csv file to be copied to the output directory of the "bin" folder and I would like to read it using the Streamreader class. After being copied to the bin folder the path looks like this: bin Debug netstandard2.0 Dataload Source code_postal.csv.

How do I inform the path "Dataload Source code.csv" and read the file from the bin folder of my project, without having to pass the full path from C: "C: user......"?

public class CodigoPostalInitializer
{
    public static void Initializer_Pat_1(RetaguardaContext context)
    {
        //List<CodigoPostal> codigoPostalList = new List<CodigoPostal>();
        CodigoPostal codigoPostal = null;
        Cidade cidade = null;



        if (!context.CodigoPostal.Any())
        {
            StreamReader reader = new StreamReader(@"C:\Users\USER\repos\retaguarda\Retaguarda\src\Retaguarda.Infra.Data\DataLoad\Source\codigos_postais.csv");

            string linha;
            while ((linha = reader.ReadLine()) != null)
            {
                string[] dados = linha.Split(',');
                string CodigoPostal = dados[0];
                string Logradouro = dados[1];
                string Complmento = dados[2];
                string Bairro = dados[3];
                string UF = dados[4];
                string Cidade = dados[5];
                string CodigoIBGE = dados[6];

                cidade = context.Cidade.FirstOrDefault(x => x.Nome.ToUpper() == Cidade.ToUpper() && (x.Estado.UF == UF || x.CodigoIBGE == CodigoIBGE));
                codigoPostal = new CodigoPostal(CodigoPostal, Logradouro, Complmento, Bairro, cidade.Id, true);
                context.Add(codigoPostal);
                context.SaveChanges();
            }

        }

        //codigoPostalList.ForEach(t => context.Add(t));

        //context.SaveChanges();

        GC.Collect(0, GCCollectionMode.Forced);
    }
}

inserir a descrição da imagem aqui

 StreamReader reader = new StreamReader(?????????);
  • Through Ihostingenvironment you use Contentrootpath, but in order not to add the ASP.NET Core reference to your infra layer, you will have to pass this when injecting. If you can provide the form you are running this Seed perhaps it is possible to provide you with a more assertive answer.

  • Thanks for the @Rafael tip. I updated the Post :)

  • I made this code as I use Seed based on a file, it doesn’t have all the treatments, but see if it solves that I elaborate an answer. https://github.com/superrfm/aspnetcoreweb_efcore

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.