Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write just an # before some rows in a text file?

Tags:

c#

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?

like image 546
uid Avatar asked Oct 09 '15 10:10

uid


1 Answers

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.

like image 143
Jon Skeet Avatar answered Sep 21 '22 03:09

Jon Skeet