C# 怎样更改文本文件(TXT)中的内容,该如何处理
C# 怎样更改文本文件(TXT)中的内容
有XXX.txt文件 内容如下:
1,B,C,D
2,C,D,E
3,D,E,F
4,E,F,G
5,a,s,d
6,....
.......
比如 我要修改第二行 2,C,D,E 修改为 9,f,g,h 怎样做
我试过用LIST<STRING>的方法 是可以的 但还有没有其他方法 学习中 !!!!!
C#有没有好像C++那样 可以将文本文件的指针移动 好像是SEEK????忘记了 高手请帮忙
不断学习的小袁上
------解决方案--------------------
有XXX.txt文件 内容如下:
1,B,C,D
2,C,D,E
3,D,E,F
4,E,F,G
5,a,s,d
6,....
.......
比如 我要修改第二行 2,C,D,E 修改为 9,f,g,h 怎样做
我试过用LIST<STRING>的方法 是可以的 但还有没有其他方法 学习中 !!!!!
C#有没有好像C++那样 可以将文本文件的指针移动 好像是SEEK????忘记了 高手请帮忙
不断学习的小袁上
------解决方案--------------------
- C# code
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));
------解决方案--------------------
------解决方案--------------------
- C# code
string[] line; line = File.ReadAllLines("12.txt",System.Text.Encoding.Default); line[1] = "9,f,g,h"; File.WriteAllLines("12.txt", line);
------解决方案--------------------
用文件流的方式比较好
- C# code
//把这个方法直接复制到你的项目中,后面直接调用就行了 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前面多打了一个空格,不好意思
- C# code
EditFile(2, "9,f,g,h" ,"c:\\test.txt");//第一个参数是指定修改的行数,第二个参数是你要保存的值,第三个参数是这个文件的路径