StreamWriter couldn't append data in file

K

Kevien Lee

Hi ,
I had a strang problam ,when i use StreamWriter to append to a file,i
found that if i don't close the
StreamReader it couldn't write the data into file,the code as folllow
that:
class Program
{
static void Main(string[] args)
{
FileInfo file = new FileInfo(@"E:\Demo\Log\20061214.log");
StreamWriter debugWriter = new
StreamWriter(file.Open(FileMode.Append, FileAccess.Write,
FileShare.ReadWrite));

debugWriter.Write("dasdasdasdsadsadsadasdasd123354856");
debugWriter.Close();
}
}

however,if remove the debugWriter.Close(),the problam show,why ?can
anyone help me?

Thanks
 
M

Morten Wennevik

Hi Kevien,

When you write using a StreamWriter, you are just writing to the buffer,
not to the underlying stream. This buffer is flushed to the underlying
stream using Flush or Close, or by setting AutoFlush = true.

When you call debugWriter.Close the buffer is flushed to the file.

A good method to ensure you flush the buffer is the 'using' statement
which will automatically call close/dispose on the object when it goes out
of scope.


static void Main(string[] args)
{
FileInfo file = new FileInfo(@"E:\Demo\Log\20061214.log");
using(StreamWriter debugWriter = new
StreamWriter(file.Open(FileMode.Append, FileAccess.Write,
FileShare.ReadWrite)))
{
debugWriter.Write("dasdasdasdsadsadsadasdasd123354856");
}
}


Hi ,
I had a strang problam ,when i use StreamWriter to append to a file,i
found that if i don't close the
StreamReader it couldn't write the data into file,the code as folllow
that:
class Program
{
static void Main(string[] args)
{
FileInfo file = new FileInfo(@"E:\Demo\Log\20061214.log");
StreamWriter debugWriter = new
StreamWriter(file.Open(FileMode.Append, FileAccess.Write,
FileShare.ReadWrite));

debugWriter.Write("dasdasdasdsadsadsadasdasd123354856");
debugWriter.Close();
}
}

however,if remove the debugWriter.Close(),the problam show,why ?can
anyone help me?

Thanks
 
M

Marc Gravell

I'm not sure I understand what you are saying... however, if you leave
a file open then it is not guaranteed to commit unflushed data. What
exactly are you seeing? And note that you should probably be "using"
the writer.

Marc
 

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

Similar Threads

question from e-learning 1
size of a file and unicode 6
log file 1
about compression 2
ASP.NET StreamWriter error 6
"Bad Data" error and issues with Streams 4
file [?] 7
file [?] 2

Top