How to replace a line in a text file?

thank you very much.

Answer this question

How to replace a line in a text file?

  • maxal

    You'll have to re-write the whole file. Something like this:

    StreamReader r = new StreamReader(filenameIn);

    StreamWriter w = new StreamWriter(filenameOut);

    try {

    string line = string.Empty;

    while ((line = r.ReadLine()) != null) {

    if (line.Contains("some string")) {

    line = "some other string";

    }

    w.WriteLine(line);

    }

    }

    catch (Exception ex) {

    // handle exception

    }

    finally {

    r.Close();

    w.Close();

    }


  • dreameR.78

    That'll work fine, but it's better to use "using" to automatically dispose of object so you don't need to manually include a "finally" block:



    using (StreamReader r = new StreamReader(filenameIn))
    using (StreamWriter w = new StreamWriter(filenameOut))
    {
    try
    {
    for (;;)
    {
    line = r.ReadLine();

    if (line == null)
    break;

    if (line.Contains("some string"))
    {
    line = "some other string";
    }

    w.WriteLine(line);
    }
    }

    catch (Exception ex)
    {
    // handle exception
    }
    }




  • How to replace a line in a text file?