Как заменить конкретное слово в конкретной строке условием
привет,
У меня есть такой текстовый файл :
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
на чем-то, что уже является струной.