我想用c#编程,读取这样的文件:
...
cindy cindy0 cindy1 cindy2 cindy3
miao miao0 miao1 miao2 miao3...
我想添加类似" cindy4"和第一行的结尾。
System.IO.StreamReader file = new System.IO.StreamReader(filename);
string line = file.ReadLine();
while(line != null)
{
if (line.Contains("cindy"))
{
tmp = line.Split(' ');
file.Close();
//TO DO change in the file
break;
}
line = file.ReadLine();
}
在TODO部分,我编码如下:
System.IO.StreamWriter writer = new System.IO.StreamWriter(System.IO.File.Open(filename, System.IO.FileMode.Open));
writer.Write("cindy4");
writer.Flush();
但它不起作用。有人能给我一个例子吗?
答案 0 :(得分:2)
试试这段代码:
string[] new_text = System.IO.File.ReadAllLines("file_path");
new_text[line_number] += "text_to_add";
//the line number start from zero
//Example: first line will be: new_text[0]
//the second line will be: new_text[1]
//Etc...
System.IO.File.WriteAllLines("file_path",new_text);