【发布时间】:2013-02-19 23:00:12
【问题描述】:
我正在阅读 file.txt 使用 StreamReader 并使用 streamWriter 写作。
我想知道是否可以“只删除我创建的最后插入的行?
i'm inserting lines, but sometimes one of these inserts arestring.empty. Then It goes to anexception”...在这个异常中,我想删除我刚刚插入的那一行.
但是我重新创建文件或类似的东西,我只需要删除/擦除/删除最后一行。我可以这样做吗?
MyCode:如果你们有其他方法可以做到这一点,我将非常感谢!
使用 (StreamWriter streamW = new StreamWriter(fileFinal, true)) { if (contador == numeroCampos) { 康塔多 = 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;
}
例如:当它进入case:"numero_carteira" 并且它不为空时,它会写入正常,但是当我到达matricula 并且它为空时,它将break 并转到我创建的异常。我想删除那里的行;希望我能清楚!
【问题讨论】:
-
请清理你的代码格式。阅读/滚动浏览它时我感到头晕目眩。
-
@DJKRAZE 对不起,我不明白,真的。我与
Ctrl + K组成了我还能做什么? -
为什么不使用 stringBuilder 来生成内容,然后只写入文件一次?
-
你的case语句也在寻找一个字符串为什么不在
case "":做一个case
标签: c# winforms visual-studio-2010