Random access file IO - what is wrong with this code?

P

Phil

Problem code:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Streams {
class Program {
static void Main(string[] args) {
const string file = @"C:\Temp\file.txt";

if (File.Exists(file))
File.Delete(file);

using (StreamWriter sw = new StreamWriter(file)) {
sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");

FileStream fs = sw.BaseStream as FileStream;
Debug.Assert(fs != null);

fs.Seek(0, SeekOrigin.Begin);
sw.WriteLine("Line A");
}
}
}
}

Expected result: a file with 3 lines
Line A
Line 2
Line 3

Actual result: a file with 4 lines
Line 1
Line 2
Line 3
Line A


The Seek() is being ignored.

Obviously I am doing something wrong - any hints guys?!
 
M

Michael

Hi,

..Flush() makes it work:

sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");
sw.Flush();
FileStream fs = sw.BaseStream as FileStream;
Debug.Assert(fs != null);
fs.Seek(0, SeekOrigin.Begin);
sw.WriteLine("Line A");
sw.Flush();

not sure it's the best solution...

Mike
http://www.seeknsnatch.com
 
P

Phil

Hi,

.Flush() makes it work:

sw.WriteLine("Line 1");
sw.WriteLine("Line 2");
sw.WriteLine("Line 3");
sw.Flush();
FileStream fs = sw.BaseStream as FileStream;
Debug.Assert(fs != null);
fs.Seek(0, SeekOrigin.Begin);
sw.WriteLine("Line A");
sw.Flush();

not sure it's the best solution...

Mike
http://www.seeknsnatch.com

Thanks Michael I will give that a shot.
 

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