file witing/repositioning

B

Brian

can someone tell me why this doesn't work...I would expect to see line 1a
replace line 01 in the following code:

FileStream fs = new FileStream(@"c:\temp\myfile.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None, 8192);
StreamWriter sw = new StreamWriter(fs);

sw.WriteLine("this is line 01");
sw.WriteLine("this is line 02");
sw.WriteLine("this is line 03");
sw.BaseStream.Position = 0;
sw.WriteLine("this is line 1a");

sw.Close();
sw.Dispose();

If I use the underlying FileStream and encode the strings myself and add the
line terminators I can do it but I want to use the convienence of the
StreamWriter class.
 
A

Alberto Poblacion

Brian said:
can someone tell me why this doesn't work...I would expect to see line 1a
replace line 01 in the following code:

FileStream fs = new FileStream(@"c:\temp\myfile.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None, 8192);
StreamWriter sw = new StreamWriter(fs);

sw.WriteLine("this is line 01");
sw.WriteLine("this is line 02");
sw.WriteLine("this is line 03");
sw.BaseStream.Position = 0;
sw.WriteLine("this is line 1a");

sw.Close();
sw.Dispose();

If I use the underlying FileStream and encode the strings myself and add
the
line terminators I can do it but I want to use the convienence of the
StreamWriter class.

I have not tried this out, but I believe that besides changing the
Position of the BaseStream, you should call the Seek method on the
BaseStream to reposition the location that it is writing on the file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top