2011-09-26 134 views
0

嗨我有一个文本文件与表架构和数据时用户检查不需要架构,那么我需要删除架构并保留数据。我正在使用StreamReader来读取文件并检查一个条件,它应该删除文件中的所有行,直到它满足我的条件。 让我们说,如果我检查删除文本文件中的行

using (StreamReader tsr = new StreamReader(targetFilePath)) 
     { 
      do 
      { 
       string textLine = tsr.ReadLine() + "\r\n"; 

       { 
        if (textLine.StartsWith("INSERT INTO")) 
        { 

         // It should leave these lines 
         // and no need to delete lines 
        } 

        else 
        { 
         // it should delete the lines 
        } 

       } 
      } 
      while (tsr.Peek() != -1); 
      tsr.Close(); 

请建议我如何删除行并注意是否一个TextLine发现“INSERTINTO”它不应该从中删除任何内容。

回答

1

您读取文件中的只是你在做同样的方式。但是,如果该行不包含您要查找的内容,则只需跳过它即可。最后,无论您将哪些数据留给您,都会写入新的文本文件。

  private void button1_Click(object sender, EventArgs e) 
    { 
     StringBuilder newText = new StringBuilder(); 
     using (StreamReader tsr = new StreamReader(targetFilePath)) 
     { 
      do 
      { 
       string textLine = tsr.ReadLine() + "\r\n"; 

       { 
        if (textLine.StartsWith("INSERT INTO")) 
        { 

         newText.Append(textLine + Environment.NewLine); 
        } 

       } 
      } 
      while (tsr.Peek() != -1); 
      tsr.Close(); 
     } 

     System.IO.TextWriter w = new System.IO.StreamWriter(@"C:\newFile.txt"); 
     w.Write(newText.ToString()); 
     w.Flush(); 
     w.Close(); 
    } 
+0

您应该使用StringBuilder而不是连接字符串....取决于行数,它可以更高效 –

+0

谢谢Steve。我的答案已更新。 – 2011-09-26 13:39:55

+0

@Evan:谢谢埃文的回答 – 62071072SP

6

使用第二个文件放置只需要的行,并在过程结束时删除原始文件并将新文件重命名为目标文件。

using (StreamReader tsr = new StreamReader(targetFilePath)) 
{ 
    using (StreamWriter tsw = File.CreateText(targetFilePath+"_temp")) 
    { 
     string currentLine; 
     while((currentLine = tsr.ReadLine()) != null) 
     { 
      if(currentLine.StartsWith("A long time ago, in a far far away galaxy ...")) 
      { 
        tsw.WriteLine(currentLine); 
      } 
     } 
    } 
} 
File.Delete(targetFilePath); 
File.Move(targetFilePath+"_temp",targetFilePath); 
+1

此代码可以通过重命名原始文件而不是删除它来改进,以防发生异常。 –

4

你可以使用Linq:

File.WriteAllLines(targetFilePath, File.ReadAllLines(targetFilePath).Where(x => x.StartsWith("INSERT INTO"))); 
+0

你的方法很好,但在极端情况下,这一行代码的内存占用至少与整个文件大小一样高(charset可以提高此值)。幸运的是,有一个100GB的文本文件是不常见的;) –

+0

@SteveB:这是正确的 - 这是您在这种情况下不使用临时文件所支付的代价,所有内容都必须加载到内存中。或者可以使用'FileReadLines()'并写入临时文件,然后复制它。 – BrokenGlass

+0

即使是5MB的文件也不常见......与今天的电脑。这不会是一个大问题。它甚至可以作为过早优化来逐行工作;) –