Reputation: 172
I need to replace multiple strings in a textfile. This is my code:
List<string> list = new List<string>();
string Text = File.ReadAllText(temp);
list.Add(Text.Replace("name", name));
list.Add(Text.Replace("name2", name2));
list.Add(Text.Replace("1.0000", CR));
list.Add(Text.Replace("0.6590", CG));
list.Add(Text.Replace("0.0000", CB));
foreach (string txt in list)
{
File.WriteAllText(path, txt);
}
When I debug I can see the strings beeing replaced one after one, but when the next string is about to be replaced, the last string will then go back to its old value. Is there a way to replace multiple strings in a textfile?
Upvotes: 0
Views: 623
Reputation: 37020
You don't need a list for this, but you do need to save the changes in the resulting string each time you do a replacement, otherwise you lose the changes.
The Replace
method returns a new string with the replacement, so you can chain the calls to Replace
and it will end up returning a string with all your changes.
Here's an example:
string text = File.ReadAllText(temp)
.Replace("name", name)
.Replace("name2", name2)
.Replace("1.0000", CR)
.Replace("0.6590", CG)
.Replace("0.0000", CB);
File.WriteAllText(path, txt);
Upvotes: 6