1

我遇到了一个问题:我想找到包含某个字符串的行,但我只知道如何替换文件中的字符串或所有行,我知道命令“string.Contains”,但它似乎无法正常工作当我使用它时:我尝试使用“if(data.contains(string))”,但它仍然将所有行更改为该字符串。这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    string replaceText = "peter";
    string withText = "Gilbert";
    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(@"C:\Users\G\Documents\test.txt"))
    {
        using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(@"C:\Users\G\Documents\test.txt" + ".tmp"))
        {

            while (!streamReader.EndOfStream)
            {
                string data = streamReader.ReadLine();
                data = data.Replace(replaceText, withText);
                streamWriter.WriteLine(data);
            }
        }

    }
    using (System.IO.StreamReader streamReader = new System.IO.StreamReader(@"C:\Users\G\Documents\test.txt" + ".tmp"))
    {
        using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(@"C:\Users\G\Documents\test.txt"))
        {

            while (!streamReader.EndOfStream)
            {
                string data = streamReader.ReadLine();
                data = data.Replace(replaceText, withText);
                streamWriter.WriteLine(data);
            }

        }
    }

}

}

4

1 回答 1

1

尝试这个:

FileStream stream = File.Open("file", FileMode.Open);
StreamReader rdr = new StreamReader(rdr);
String[] flines = rdr.ReadToEnd().Split(new String[]{"\r\n"}, StringSplitOptions.None);
rdr.Close();
stream = File.Create("file");
StreamWriter wtr = new StreamWriter(stream);
foreach(String str in flines)
{
    wtr.WriteLine(str.Replace(replaceTxt, newText));
}
wtr.Close();

当然,您可以将逻辑放入循环中,根据您喜欢的任何标准更改或不更改写入的字符串。

于 2012-10-26T15:40:25.810 回答