static void FileStreamSDemo() { DateTime dtNow = DateTime.Now; DateTime dtEnd = dtNow.AddSeconds(60); using(FileStream fs=new FileStream("FileStream.t ...
static void FileStreamSDemo() { DateTime dtNow = DateTime.Now; DateTime dtEnd = dtNow.AddSeconds(60); using(FileStream fs=new FileStream("FileStream.txt",FileMode.Create)) { while (DateTime.Now < dtEnd) { string msg = $"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")},Guid is {Guid.NewGuid()}"; byte[] data = Encoding.UTF8.GetBytes(msg); fs.Write(data, 0, data.Length); } } } static void StreamWriterDemo() { DateTime dtNow = DateTime.Now; DateTime dtEnd = dtNow.AddSeconds(60); using(StreamWriter writer=new StreamWriter("StreamWriter.txt",true,Encoding.UTF8)) { while(DateTime.Now<dtEnd) { string msg = $"Now is {DateTime.Now.ToString("yyyyMMddHHmmssffff")},Guid is {Guid.NewGuid()}"; writer.WriteLine(msg); } } }
In fact,during the identical time,the streamwriter generated much more data.
In my pc,StreamWriter.txt is 2.03 GB (2,187,534,336 bytes)
While FileStream.txt is 1.86 GB (1,998,835,712 bytes),
Based on the above fact and data,The streamwriter has speed advantages.