Getting the file size from StreamWriter

Moh Moh Oo picture Moh Moh Oo · Aug 8, 2013 · Viewed 13.8k times · Source
using (var writer = File.CreateText(fullFilePath))
{
   file.Write(fileContent);
}

Given the above code, can the file size be known from StreamWriter?

Answer

Sriram Sakthivel picture Sriram Sakthivel · Aug 8, 2013

Yes, you can, try the following

long length = writer.BaseStream.Length;//will give unexpected output if autoflush is false and write has been called just before

Note: writer.BaseStream.Length property can return unexpected results since StreamWriter doesn't write immediately. It caches so to get expected output you need AutoFlush = true

writer.AutoFlush = true; or writer.Flush();
long length = writer.BaseStream.Length;//will give expected output