开发者

Delete Lines in a textfile

Hi I have a text file with table schema and data when user checks not schema required then i ne开发者_运维技巧ed to delete schema and leave the data . I am using StreamReader to read the file and checking one condition and it should delete all the lines in the file till it satisfies my condition . Let say if i am checking

  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();  

Please suggest me how to delete lines and note if textline finds "InsertInto" it should not delete any content from there .


Use a second file where to put only required lines, and, at the end of the process, remove original file and rename new one to target file.

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);


You could use Linq:

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


You read in the file just the same way you were doing. However, if the line doesn't contain what you are looking for, you simply skip it. In the end, whatever data you are left over with you then write to a new text file.

            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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜