Update a CSV line without having to go through it all c#

Asked

Viewed 259 times

0

Could I update a specific line of the CSV file? i have the information of which line I want to add information, currently I have the code that goes through the file and when it arrives in the line I want it updates the line and continues writing the rest of the lines, however this is causing me a loss of performasse, because my file is very large, if someone knows how to edit using some parameter to go straight to the line as if it were an array?

   public  string EscreveCSV(string caminho, int linha, string mensagem)
    {
        //Só continua se o arquivo informado existir
        if (File.Exists(caminho))
        {
            //lista que irá armazenar cada linha do arquivo
            List<string> linhas = new List<string>();


            using (TextReader tr = new StreamReader(caminho, Encoding.Default))
            {
                string sLinha = null;
                while ((sLinha = tr.ReadLine()) != null)
                {
                    linhas.Add(sLinha); //adiciona cada linha do arquivo à lista
                }

                tr.Close();
                tr.Dispose();

            }

            //Só continua se o arquivo ter um número maior de linhas informadas
            if (linhas.Count > linha)
            {
                linhas[linha] += ";" + mensagem; //adiciona a mensagem informada ao final da linha

                using (TextWriter tw = new StreamWriter(caminho, false, Encoding.Default))
                {
                    foreach (string l in linhas)
                    {
                        tw.WriteLine(l); //escreve no arquivo novamente
                    }

                    tw.Close();
                }

                return "Arquivo Escrito com sucesso"; //mensagem de retorno
            }
            else
            {
                return "Arquivo Não possui a linha informada";
            }
        }
        else
        {
            return "Arquivo não existe";
        }
    }
  • Post the current code

  • 1

    Ready @Virgilionovic

  • Take a look here https://superuser.com/questions/7169/querying-a-csv-file

  • @Denis, I looked but did not find how it could help me and I believe he is not using the C#

  • There is a way to pick up all the lines, then make the check after recording again, maybe (without testing has no way to say if it is more performatic) because, if you do the manual process is should be very time consuming

  • CSV is a text file, unless the new line has exactly the same number of characters as the one being overwritten it has no way to change without recreating the entire file

  • @Virgilionovic I’ll see if I can do something following that line of reasoning

  • @Leandrogodoyrosa would not replace but add information at the end of the line

  • @Jhonatassilva I’m going to propose a test sketch and tell me what happened if it was more performatic.

  • @Jhonatassilva how many lines your file has?

  • @Virgilionovic I am trying with a file that has 206 columns and 300 lines but I do validation in all fields/ line, then when I find an error this validation call the method that writes this error in CSV

  • @Jhonatassilva is not better to open the file in memory, check the error, change, and then until it’s over and write everything!?

  • Memory manipulation is always better, unless to make a loose change and close right after

  • I thank everyone for the comment, it was very valid, I managed to solve the problem, instead of reading and recording in the spreadsheet (CSV) all the time and I threw the information in a list, I do all the manipulation of the data I need and only at the end write in CSV, much increase to performasse, I will put here share the code that lists the spreadsheet initially, and what updates in the lines I need.

Show 9 more comments

1 answer

0

Code Using to Pass CSV Content to a String List:

 public List<string> PlanilhaCSV(string caminho)
    {
        DataTable dt = new DataTable();
        List<string> lista = new List<string>();

        try
        {
            using (StreamReader rd = new StreamReader(caminho))
            {

                string linha = null;


                while ((linha = rd.ReadLine()) != null)
                {

                    lista.Add(linha.ToString());

                }

                rd.Close();
                rd.Dispose();

                    return lista;


            }
        }

        catch (Exception)
        {

            Console.WriteLine("Não foi possivel localizar o arquivo " + caminho);

        }
        return lista;
    }

//Code used to add an error log to a specific line

     public List<string> AdionaLog(List<string> lista, int linha, string mensagem)
    {
        List<string> linhas = new List<string>();
        int contador = 1;
        foreach (var x in lista)
        {


            if (contador == linha)
                linhas.Add(x + ";" + mensagem);

            else
                linhas.Add(x.ToString());

            contador++;
        }



        return linhas;


    }

// Finally writing in the spreadsheet the contents of the List

   public void PlanilhaSaida(List<string> lista, string caminho)
    {


        using (TextWriter tw = new StreamWriter(caminho, false, Encoding.UTF8))
        {
            foreach (string l in lista)
            {
                tw.WriteLine(l);
            }

            tw.Close();
        }




    }

Browser other questions tagged

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