Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
we were facing a problem that sometime the file was not written completely (all the data) and we were using code below

C#
using (FileStream fs = new FileStream(tempFileName, FileMode.Create))
                {
                    BinaryWriter writer = new BinaryWriter(fs);
                    writer.Flush();
                    writer.Write(data);
                }  


only thing i did to solve the situation is put
C#
fs.Close();


inside using statement and it's started working as expected. now as per MSDN says diposed does call close internally.

any idea why this strange behavior ?
Posted
Comments
Rob Philpott 8-Dec-14 9:10am    
Interesting. I can see why it may not work now, (data is in the BinaryWriter buffer and may not be written to stream until the flush), but not why explicitly calling Close() on the filestream would fix it.

I'd be interested to find out!

1 solution

Change your code to below code.

C#
using (FileStream fs = new FileStream(tempFileName, FileMode.Create))
{
      BinaryWriter writer = new BinaryWriter(fs);
      writer.Write(data);
      writer.Flush();
}  


Do a Flush() after write.
 
Share this answer
 
Comments
Praveen Kumar Upadhyay 8-Dec-14 8:35am    
You can also refer the below link.

http://stackoverflow.com/questions/12735897/streamwriter-is-cutting-off-my-last-couple-of-lines-sometimes-in-the-middle-of-a
CS2011 8-Dec-14 8:45am    
well i know flush will do the job so will close(). my question is while under using statement disposed get called and inside dispose close() gets called. so why data is not written properly when i use it without calling close manually
Praveen Kumar Upadhyay 8-Dec-14 9:00am    
If you are using Flush() after write, you don't need to use Close(). There is some problem of using 'using' statement. Check out below link.

http://msdn.microsoft.com/en-us/library/aa355056(v=vs.110).aspx
CS2011 8-Dec-14 13:10pm    
buddy see the question. as per MS calling dispose calls close internally which calles flush() but it doesn't happen sometime but when i call close in my code it works as expected. my question is why it happens. Just do not post anything as answer for points

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900