1

ive got a problem: i want to find a line containing a certain string, but i only know how to replace the string in the file or all the lines, i know the command "string.Contains", but it doesnt seem to work properly as i use it: i tried to use "if (data.contains(string))", but then it still changes all the lines to that string. heres my code:

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

        }
    }

}

}

2
  • 2
    what exactly are you trying to do? just find a string in a txt file and then what?
    – Stan R.
    Oct 26, 2012 at 15:30
  • Like @StanR. said, please explain, in detail, what you are trying to do.Until then, you should consider writing out your text file content to a StringBuilder and then work with that StringBuilder object to get the text exactly how you want it, then write out the SB object content to your text file (or a new text file). Keep in mind that your code is creating many string objects in your while statement.
    – Jed
    Oct 26, 2012 at 15:39

1 Answer 1

1

Try this:

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

Of course you could put logic in the loop the either change or not change the string written based on whatever criterion you like.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.