Reputation: 197
I want to replace String1 with String2 in Text file.
Text File :
This is line no 1.
This is line no 2.
This is line no 3.
This is line no 4.
This is line no 5.
This is line no 6.
String is :
String1 : no
string2 : number
I want this type of output line 3 to 5 replace with "no" to "number":
This is line no 1.
This is line no 2.
This is line number 3.
This is line number 4.
This is line number 5.
This is line no 6.
Upvotes: 1
Views: 4788
Reputation: 46005
Another approach with Linq
string[] file = File.ReadAllLines(@"c:\yourfile.txt");
file = file.Select((x, i) => i > 1 && i < 5 ? x.Replace("no", "number") : x).ToArray();
File.WriteAllLines(@"c:\yourfile.txt", file);
Upvotes: 7
Reputation: 1081
System.IO.File.ReadAllLines(string path)
may help you.
It creates string array from Text File, you edit the array, and save it with System.IO.File.WriteAllLines
.
string[] Strings = File.ReadAllLines(/*File Path Here*/);
Strings[2] = Strings[2].Replace("no", "number");
Strings[3] = Strings[3].Replace("no", "number");
Strings[4] = Strings[4].Replace("no", "number");
File.WriteAllLines(/*File Path Here*/, Strings);
Upvotes: 1
Reputation: 815
You should try this:
// Read all lines from text file.
String[] lines = File.ReadAllLines("path to file");
for(int i = 3; i <= 5; i++) // From line 3 to line 5
{
// Replace 'no' to 'number' in 3 - 5 lines
lines[i - 1] = lines[i - 1].Replace("no", "number");
}
// Rewrite lines to file
File.WriteAllLines("path to file", lines);
Upvotes: 0