Rafik Bari
Rafik Bari

Reputation: 5037

How to replace a line within a text file regardless to its current value?

I want to replace a line inside the Preferences file of Google Chrome in order to change current homepage.

In my computer, i've http://www.google.com which is defined as a default homepage, and therefor i need to replace (inside the Preferences file) the following line :

         "homepage": "http://www.google.com/",

Replace with :

         "homepage": "http://www.MyWebsite.com/",

So in order to do this, i am using a code which look something like this :

          string PreferencesFile = File.ReadAllText(file);
          PreferencesFile.Replace(FirstLine,SecondLine);
          File.WriteAllText(file,PreferencesFile);

But the problem is that in each computer, there is a different homepage.

How to replace the line below

         "homepage": "http://www.what-ever-site-is-here.com/",

With

         "homepage": "http://www.MyWebsite.com/",

And which values should be affected to FirstLine and SecondLine variable ?

Upvotes: 0

Views: 125

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504172

Sounds like you should read all the lines, replace any line starting with "homepage": and then rewrite. For example:

var lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
    if (lines[i].StartsWith("\"homepage\": "))
    {
        lines[i] = "\"homepage\": \"http://www.MyWebsite.com\"",";
    }
}
File.WriteAllLines(file, lines);

Upvotes: 2

Related Questions