Use a
for
loop instead of a
foreach
loop, and only write the updated content back to the file outside of the loop.
for (int index = 0; index < lines.Length; index++)
{
string line = lines[index];
if (line.Contains(oldText))
{
lines[index] = newText;
}
}
File.WriteAllLines(pathFile, lines);
NB: Since
csproj
files are XML, it may be safer to load and manipulate them using an XML parser - eg:
LINQ to XML[
^].