Click here to Skip to main content
15,799,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a text file like this :

SERVER = localhost$
SERVERM = localhost$

I need to replace "localhost" in SERVER = localhost$ with any value...

What I have tried:

I tried to write this code

public static string readConfTextStartWith(string path, string startsWith)
            string Value = "";
            foreach (var line in File.ReadLines(path))
                if (line.StartsWith(startsWith))
                    string str = line.Split('=')[1].Trim();
                    Value = Convert.ToString(str.Substring(0, str.Length - (str.Length - str.LastIndexOf('$'))));
            return Value;
        public static void replaceText(string path, string startsWith, string replacement)
            string word =  readConfTextStartWith(path, startsWith);
            using (StreamReader reader = new StreamReader(path))
                string line;
                while ((line = reader.ReadLine()) != null)
                    if (line.StartsWith(startsWith))
                        line = line.Replace(word, replacement);
                        // here what i can't to do 
                        // i went to write one line but this code clear all text and add this line only 
                        File.WriteAllText(path, line);


Functions.replaceText("configA.txt", "SERVER","localhost");
Updated 28-Jan-18 6:30am
Richard MacCutchan 28-Jan-18 11:23am    
You need to read all the lines into a List, modify the list and then write all the lines from the list. preferably into a new file. Also you do not need to call Convert.ToString on something that is already a string.

1 solution

Try a regex:
public static Regex regex = new Regex("(?<=SERVER\\s*=\\s*)localhost(?=\\$)",
    | RegexOptions.Singleline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
string inputText = File.ReadAllText(pathToFile);
string result = regex.Replace(inputText,"Hello world!");
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900