StreamWriter Seeking [C#]

Shaitan00

Well-known member
Joined
Aug 11, 2003
Messages
343
Location
Hell
Given a file [info.txt], and a string [line] I want to seek inside the file to a certain point and insert the line.

[Info.txt]:
// This is the contents of info.txt
// there are instructions here that must not be overwritten
4456 : 1st Inst
4457 : 2nd Inst
4470 : 3rd Inst

[string line]
 
my suggestion:

Code:
//Creating a File - just for testing...
StreamWriter writer1 = new StreamWriter("test.txt",false);
for(int i = 1; i < 129; i++)
	writer1.WriteLine("{0}: this is line {0}",i);
writer1.Close();
writer1 = null;

//the new line..
string newLine109 = "109: this is the 2nd version of line 109";
string LineNumber = newLine109.Substring(0,newLine109.IndexOf(:));

StreamReader reader1 = new StreamReader("test.txt");

string newValue = "";

while(reader1.Peek()!=-1)
{
	string tmpValue = reader1.ReadLine();

	if(tmpValue.StartsWith(LineNumber))
		newValue += newLine109 + Environment.NewLine;
	else
		newValue += tmpValue + Environment.NewLine;
}

reader1.Close();

StreamWriter writer2 = new StreamWriter("test.txt",false);
writer2.Write(newValue);
writer2.Close();
 
I use a similar method to seek out the appropriate line however your example below [as with my current code] does not OverWrite the line it Appends to it, so the result you would see on line 129 would be the previous line and appended your newValue string.

Is there not a way to OverWrite/Replace the line with newValue string not append to it?
 
Back
Top