zrubi zrubi - 3 months ago 10
C# Question

How to overwrite next line after found line in text document

here I want one thing, so I take line from some value, found it in text document and now I want overwrite X not over the found line, but over the next line coming after this found line

so if content is:

line1
line2
line3
line4


and if
string text = "line2";
with this code:

using System;
using System.IO;

namespace _03_0
{
class Program
{
static void Main(string[] args)
{
string text = "line2";

string text = File.ReadAllText("doc.txt");
text = text.Replace(text, "X");
File.WriteAllText("doc.txt", text);
}
}
}


I have this result:

line1
X
line3
line4


but I want this result:

line1
line2
X
line4

Answer

I suggest using Regular Expressions for this:

string filePath = @"doc.txt";
string myStr = "line2";
string content = File.ReadAllText(filePath);
string pattern = string.Format(@"(?<={0}\r\n).+?(?=\r\n)", myStr);
Regex r = new Regex(pattern);
File.WriteAllText(filePath, r.Replace(content, "X"));

P.S: you'll need to import RegularExpressions namespace:

using System.Text.RegularExpressions;

Hope that helps :)

A side note: You can't use the same variable name (text) twice.