2013-02-19 4 views
2

나는 file.txt을 읽고 StreamReader을 사용하고 streamWriter을 사용하여 글을 읽고 있습니다.file.txt의 마지막 줄을 삭제하는 방법

나는 그것이 내가 만든 exception`that 그냥 마지막 INSERTED LINE ? i'm inserting lines, but sometimes one of these inserts are String.Empty로 . Then It goes to an을 'DELETE에 ...이 예외에, 난 그냥 삽입 된 행을 삭제할 수 있는지 알고 싶습니다

.

하지만 파일을 다시 만들거나 마지막 줄을 삭제/지우기/삭제하기 만하면됩니다. 내가 할 수 있을까?

MyCode :이 작업을 수행하는 다른 방법이 있다면 매우 감사 할 것입니다.

사용 (StreamWriter를 streamW = StreamWriter는 새로운 (fileFinal) TRUE) { 경우 (콘타 도르 == 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 것이다. 나는 거기 선을 삭제하고 싶다; s 희망은 나쁠 수 있었다! 그래서 당신은 마지막을 제외한 모든 라인을 작성해야

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

: 파일이 너무 크지 않으면

+0

코드의 서식을 정리하십시오. 나는 현기증 읽기/스크롤링을하고 있습니다. – MethodMan

+0

@DJKRAZE 미안하지만, 정말 그럴 수 없습니다. 나는'Ctrl + K '와 함께 formmated 할 수 있을까요? – Ghaleon

+0

stringBuilder를 사용하여 내용을 작성한 다음 한 번만 파일에 쓰는 이유는 무엇입니까? – Dhawalk

답변

7

, 당신은 단순히이 코드를 사용할 수 있습니다.

+0

나는 'Take'의 사용을 좋아한다 –

+0

이 방법은 정확히 무엇을 할 것인가? 내가 파일을 덮어 쓸 수 없거나 파일을 다시 만들 수 없기 때문에 묻습니다. 오, 처음에는 전체 파일을 읽고 그 모든 내용을 읽었을 것입니다.하지만 마지막 줄은 "lengh -1"입니다. – Ghaleon

+0

@ Ghaleon : 예. 파일을 덮어 쓸 수없는 이유는 무엇입니까? 그게 마지막 줄을 "제거"할 때 기본적으로하는 일입니다. –

관련 문제