Write CSV file in a certain line passed by parameter c#

Asked

Viewed 1,057 times

0

How to write in a CSV file, in a certain line I will receive by parameter, example of the beginning of the code:

 public void EscreverCSV(string caminho, int linha, string mensagemErro)

    {
        using (StreamWriter wt = new StreamWriter(caminho))
        {


        }
    }
  • line from where ? integer ? to q this message ?

  • i have a CSV file that contains several lines separated by ; (point and comma), I want to call this method and tell it to add a text ( the Rro message parameter) on the line ( number passed by parameter also)

  • example: I want line 5 to add the message "not inserted"

  • Then it would be edit, or add a field in line i of the given CSV file

  • exactly Rovann, would you be so kind as to help me in this?

1 answer

0

You can read the file, store each row in one List<>, fetch the line you need to change, and write to the file again.

Remembering that the line index starts at 0.

Follow the commented code:

using System;
using System.Text;
using System.Collections.Generic;
using System.IO;

...

public static 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();    
        }

        //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";    
    }
}

put in the . Netfiddle: https://dotnetfiddle.net/ld7vTQ

  • Rovann, gave error in reading the file, says the file is already being used by another process, I believe it is because it was opened in Streamwrite ai when we try to read the same spreadsheet of the error.

  • the StreamReader and StreamWriter at the end of the process are closed, make sure the file is not open in another program on your computer

  • which line exactly occurs error ?

  • I have already checked and is not open, the error na in the following line:

  • using (Textreader tr = new Streamreader(path, Encoding.Default))

  • edited the comment because confuse the line of error, now this right, it is this line quoted above that happens the error.

  • o C# then can not even read the file, certainly it is being used, try to make a copy of the file, and test with it

  • I did this tmb, then closed the connection of Streamwriter ( tw.Close();) to test and "it worked", only then we could not get it to work as we hope.

  • but the TextWriter is after, not making much sense this. made some change in the code ?

  • Dude on the first try I think I copied from dotnetfiddle.net there made one more attempt copying your code here, it seems wt. Close() was not releasing the file so I put down the wt.Dispose and it worked, man thanks a lot for the help, I was breaking my head here.

  • how I’m using the using there is no need for the Dispose but, if you managed to make it work, good, don’t forget to mark it as a reply. Thanks @Jhonatassilva

Show 6 more comments

Browser other questions tagged

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