2

I'm reading a file.txt using StreamReader and writing using streamWriter.

I'd like to know if it's possible to ´DELETE JUST THE LAST INSERTED LINE? i'm inserting lines, but sometimes one of these inserts arestring.empty. Then It goes to anexception`that I created... In this exception, I want to delete that line I just inserted.

But I recreate the file, or something like that, I need just to remove/erase/delete the last line. May I do that ?

MyCode: IF you guys have another way to do this, i'd be very thankfull !

using (StreamWriter streamW = new StreamWriter(fileFinal, true)) { if (contador == numeroCampos) { contador = 0; }

  foreach (string s in clb_frente_impressao.Items) 
    {                            
    if (camposEscritos >= 10 * numeroCampos) 
      {
        streamW.WriteLine();
        streamW.WriteLine("-------------------------------------------------------");
        streamW.Write(nomearquivo + x.ToString());
        streamW.WriteLine();
        x++;
        camposEscritos = 0;
       }

       if (contador >= clb_frente_impressao.Items.Count)
          {
            contador = 0;
          }
       switch (s)
         {
            case "numero_carteira":
            if (campos_obrigatorios.Contains("numero_carteira") && campo.numero_carteira == "")
               {
                 dados_inexistentes++;
                 skipToNext = true;
                 break;
                }
                else if (campo.numero_carteira != "")
                   {
                      string aux = "";
                      qtdZeros = Txt_qtdZeros.Text;
                      if (qtdZeros == "")
                        {
                           qtdZeros = "8";
                        }
                   while (campo.numero_carteira.Length < Convert.ToInt32(qtdZeros))
                       {
                         campo.numero_carteira = campo.numero_carteira.Insert(0, "0");
                       }

                    if (usaC == "sim")
                        {
                      campos += @"\" + "*C" + aux + campo.numero_carteira + "*" + @"\";
                                                camposEscritos++;
                         }
                                            else
                                            {
                                                campos += @"\" + "*" + aux + campo.numero_carteira + "*" + @"\";
                                                camposEscritos++;
                                            }

                                            if (contador == 0)
                                            {
                                                streamW.WriteLine();
                                                streamW.Write("{0,-15}", campo.numero_carteira);
                                                contador++;
                                            }
                                            else
                                            {
                                                streamW.Write("{0,-15}", campo.numero_carteira);
                                                contador++;
                                            }
                                        }
                                       break;

                                    case "matricula":
                                       if (campos_obrigatorios.Contains("matricula") && campo.matricula == "")
                                       {
                                           dados_inexistentes++;
                                           skipToNext = true;
                                           break;
                                       }
                                        camposEscritos++;
                                        if (campo.matricula != "")
                                        {
                                            if (campo.tipo_pessoa == "3")
                                            {
                                                campos += @"\" + campo.matricula + "-" + campo.cod_dependente + @"\"; 
                                            }
                                            else
                                            {
                                                campos += @"\" + campo.matricula + @"\"; 
                                            }
                                        }
                                        if (contador > 0)
                                        {
                                            if (campo.cod_dependente != "")
                                            {
                                                streamW.Write("{0,-10}", campo.matricula + "-" + campo.cod_dependente);                                            
                                                contador++;
                                            }
                                            else
                                            {                                            
                                                streamW.Write("{0,-10}", campo.matricula);
                                                contador++;
                                            }
                                        }
                                        else
                                        {
                                            if (campo.cod_dependente != "")
                                            {
                                                streamW.WriteLine();
                                                streamW.Write("{0,-10}", campo.matricula + "-" + campo.cod_dependente);
                                                contador++;
                                            }
                                            else
                                            {
                                                streamW.WriteLine();
                                                streamW.Write("{0,-10}", campo.matricula);
                                                contador++;
                                            }
                                        }
                                        break;
  if (skipToNext) break;

                        } //Final do ForEach

                        if (skipToNext)
                        {
                            //HERE IS WHERE I WANT TO DELETE THE LAST LINE THAT WAS WRITED BY streamW
                            continue;
                        }

e.g: When It gets into case:"numero_carteira" and it's not empty,then it writes ok, but when I get to the matricula AND its empty, it will break and go to the exception I created. I want to delete the line there ;s Hope I could be clear !

Ghaleon
  • 1,186
  • 5
  • 28
  • 55

1 Answers1

7

If the file is not too large, you can simply use this code:

var lines = File.ReadAllLines(pathToFile);
File.WriteAllLines(pathToFile, lines.Take(lines.Length - 1));

So you have to write all lines except the last.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • What will this method do exactly? I'm asking that because I cant overwrite the file or recreate one ;s Ohh, I guess it first read the whole file and write everything tha has been read but the last line, that's why the `lengh -1` right ? – Ghaleon Feb 19 '13 at 17:12
  • @Ghaleon: Yes. Why can't you overwrite the file? That's what you're basically doing when you want to "remove" the last line. – Tim Schmelter Feb 19 '13 at 17:15
  • @TimSchmelter Remeber my last post that you helped me ? Well, i'm creating something like a TABLE on a file.txt, so the column's name can not be erased, that's why I need just to remove the last line, OR get another way to do all of this... I'm getting crazy with that ;x – Ghaleon Feb 19 '13 at 17:35
  • @TimSchmelter but there's something we must change... When execute the code `File.WriteAllLines(pathToFile, lines.Take(lines.Length - 1));` It erase the line correct, but leaves a `blank line`, I don't want it ;s IS there a way to work around it ? – Ghaleon Feb 19 '13 at 19:11
  • Ghaleon: It does not erase a line. It writes all lines in the file, every line ends with a line break. That why you think that the last line is empty. Actually there is nothing in the last line. Have a look at this thread: http://social.msdn.microsoft.com/Forums/da-DK/csharpgeneral/thread/ced78427-e8fc-41ee-a702-e7bcb719e28e Use the `StreamWriter` approach if you want to prevent the last line break. – Tim Schmelter Feb 19 '13 at 19:20