I have a text file who are like this :
Rows
...
product.people
product.people_good
product.people_bad
product.boy
#product.me
...
Rows
I want to put # before product.
and the file to be :
Rows
...
#product.people
#product.people_good
#product.people_bad
#product.boy
#product.me
...
Rows
For this I use next code :
string installerfilename = pathTemp + fileArr1;
string installertext = File.ReadAllText(installerfilename);
var linInst = File.ReadLines(pathTemp + fileArr1).ToArray();
foreach (var txt in linInst)
{
if (txt.Contains("#product="))
{
installertext = installertext.Replace("#product=", "product=");
}
else if (txt.Contains("product.") && (!txt.StartsWith("#")))
{
installertext = installertext.Replace(txt, "#" + txt);
}
File.WriteAllText(installerfilename, installertext);
}
But this code do the next thing:
Rows
...
#product.people
##product.people_good
##product.people_bad
#product.boy
#product.me
...
Rows
Someone can explain me way ? And how I can write just one # before that rows?
Currently you're reading the same text file twice - ones as individual lines and once as a whole thing. You're then rewriting a file as many times as you have lines. This is all broken. I suspect you simply want:
// Note name changes to satisfy .NET conventions
// Note: If pathTemp is a directory, you should use Path.Combine
string installerFileName = pathTemp + fileArr1;
var installerLines = File.ReadLines(installerFileName)
.Select(line => line.StartsWith("product=") ? "#" + line : line)
.ToList();
File.WriteAllLines(installerFileName, installerLines);
If you were writing to a different file than the one you were reading from, you wouldn't need the ToList
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With