在c#中搜索并添加新行

时间:2017-01-22 09:41:03

标签: c# search append file-writing

我有这样的代码:

reset <= '1';
ds <= '0';
wait for 20ns;
wait until clk = '0';
reset <= '0';
wait until clk = '1';
wait until clk = '0';
inexp <= x"00903ad9";
inmod <= x"03b2c159";
report "clock init";
indata <= x"72624326";
wait until clk = '1';
wait for 2ns;
ds <= '1';
wait until ready = '0';
ds <= '0';
wait until ready = '1';
wait for 500ns;
reset <= '1';
ds <= '0';
wait for 20ns;
wait until clk = '0';
reset <= '0';

我希望在每一行中搜索"<="并在此行之前添加一个追加新行。(写入文件) 我在我的代码中找到了这个词,但是对于追加不知道! 通过以下代码获取并给出行:

    int counter = 1;
    string line;

    System.IO.StreamReader file = new System.IO.StreamReader("e:\\file.txt");
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("<="))
        {
            Console.WriteLine(counter.ToString() + ": " + line);                    
        }
        counter++;
    }

    file.Close();

由于

1 个答案:

答案 0 :(得分:2)

要写入文件新文本,请将代码更改为:

System.IO.StreamReader file = new System.IO.StreamReader("e:\\file.txt");
System.IO.StreamWriter resultFile = new System.IO.StreamWriter("e:\\resultFile.txt", false);
while ((line = file.ReadLine()) != null)
{
    if (line.Contains("<="))
    {
        resultFile.WriteLine(Environment.NewLine + counter.ToString() + ": " + line);                    
    }

    // if you don't want to write lines without "<=" - delete "else" block
    else
    {
        resultFile.WriteLine(counter.ToString() + ": " + line);    
    }
    counter++;
}

在此代码中,您可以创建新文件并将file.txt中的每一行写入其中。如果行包含<=,则在开头添加新行。

因此,在磁盘E中,您会找到包含所需文本的新文件resultFile.txt