日期:2014-05-18 浏览次数:21407 次
string[] content = System.IO.File.ReadAllText("E:\\test.txt").Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); content[1] = "9,f,g,h"; System.IO.File.WriteAllText("E:\\test.txt", string.Join("\r\n", content));
------解决方案--------------------
string[] line; line = File.ReadAllLines("12.txt",System.Text.Encoding.Default); line[1] = "9,f,g,h"; File.WriteAllLines("12.txt", line);
------解决方案--------------------
用文件流的方式比较好
//把这个方法直接复制到你的项目中,后面直接调用就行了 public static void EditFile(int curLine, string newLineValue, string patch) { FileStream fs = new FileStream(patch, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")); string line = sr.ReadLine(); StringBuilder sb = new StringBuilder(); for (int i = 1; line != null; i++) { sb.Append(line + "\r\n"); if (i != curLine - 1) line = sr.ReadLine(); else { sr.ReadLine(); line = newLineValue; } } sr.Close(); fs.Close(); FileStream fs1 = new FileStream(patch, FileMode.Open, FileAccess.Write); StreamWriter sw = new StreamWriter(fs1); sw.Write(sb.ToString()); sw.Close(); fs.Close(); }
------解决方案--------------------
刚刚9前面多打了一个空格,不好意思
EditFile(2, "9,f,g,h" ,"c:\\test.txt");//第一个参数是指定修改的行数,第二个参数是你要保存的值,第三个参数是这个文件的路径