Neir0
Neir0

Reputation: 13367

simultaneously read and write data into file

i want simultaneously read and write data into file. Can i use StreamReader and StreamWriter with only file? And why code below doesnt out numbers?

var stream = new FileStream(path,FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);
var sw = new StreamWriter(stream);
var sr = new StreamReader(stream);


for(int i=0;i<10;i++)
{
    sw.WriteLine(i);
}

stream.Seek(0,SeekOrigin.Begin);
for(int i=0;i<10;i++)
{
 Console.WriteLine(sr.ReadLine());
}

stream.Close();

Upvotes: 2

Views: 2047

Answers (1)

SLaks
SLaks

Reputation: 887453

You need to Flush the StreamWriter to force it to actually write the data from its internal buffer to the stream.
Alternatively, you can set the StreamWriter's AutoFlush property to true

Upvotes: 2

Related Questions