I'm reading a file.txt
using StreamReader
and writing using streamWriter
.
? i'm inserting lines, but sometimes one of these inserts are
string.empty. Then It goes to an
exception`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 !