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

CHECK_CONFIG = 0$
LANGUAGE = en$
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

C#
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);

                    }
                }
                reader.Close();
            }
        }

Functions.replaceText("configA.txt", "SERVER","localhost");
Posted
Updated 28-Jan-18 5:30am
v2
Comments
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.Multiline
    | RegexOptions.Singleline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );
...
string inputText = File.ReadAllText(pathToFile);
string result = regex.Replace(inputText,"Hello world!");
 
Share this answer
 
v2

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