在C#中更改包含特定字符串的文件中的一行

时间:2012-10-26 15:12:42

标签: c#

我有一个问题:我想找到一个包含某个字符串的行,但我只知道如何替换文件中的字符串或所有行,我知道命令“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);
            }

        }
    }

}

}

1 个答案:

答案 0 :(得分: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();

当然你可以在循环中输入逻辑,或者根据你喜欢的标准改变写的字符串。