1)File类
//找到setLocation
string[] ary = File.ReadAllLines(path, Encoding.Default);
ary = ary.Select(t => t.Trim().StartsWith("setLocation") ? setLocation : t.Trim()).ToArray(); File.WriteAllLines(path, ary, Encoding.Default);
2)StreamReader类
string text = "";
using (StreamReader reader = new StreamReader(path, Encoding.Default)) { string line = reader.ReadLine(); while (line != null) { //如果这一行以setLocation开始,就替换原来的信息 if (line.StartsWith("setLocation")) { line = setLocation; } text += line + "\r\n"; line = reader.ReadLine(); } reader.Close(); reader.Dispose(); } //写入流,更新数据 using (StreamWriter writer = new StreamWriter(path)) { writer.Write(text); writer.Close(); writer.Dispose(); }