Golden Basim Ответов: 1

Как заменить конкретное слово в конкретной строке условием


привет,
У меня есть такой текстовый файл :

CHECK_CONFIG = 0$
LANGUAGE = en$
SERVER = localhost$
SERVERM = localhost$


Мне нужно заменить "localhost" в SERVER = localhost$ с любой ценностью...

Что я уже пробовал:

Я пытался написать этот код

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");

Richard MacCutchan

Вам нужно прочитать все строки в список, изменить список, а затем записать все строки из списка. желательно в новый файл. Также вам не нужно звонить Convert.ToString на чем-то, что уже является струной.

1 Ответов

Рейтинг:
9

OriginalGriff

Попробуйте регулярное выражение:

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!");