Reputation: 947
I want to program in c#, read a file like this:
...
cindy cindy0 cindy1 cindy2 cindy3
miao miao0 miao1 miao2 miao3
...
And I want to add something like "cindy4" and the end of the first line.
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();
}
In the TODO part, I code like this:
System.IO.StreamWriter writer = new System.IO.StreamWriter(System.IO.File.Open(filename, System.IO.FileMode.Open));
writer.Write("cindy4");
writer.Flush();
But it does not work. Could somebody get me an example?
Upvotes: 3
Views: 114
Reputation: 89
Try this code:
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);
Upvotes: 2