C# BinaryWriter BinaryReader demo
static void BinaryWriterReaderDemo() { using (FileStream fs = new FileStream("fs.txt", FileMode.Create)) { SaveData(fs); } using(FileStream fs=new FileStream("fs.txt",FileMode.Open)) { using (BinaryReader br = new BinaryReader(fs)) { int fsLength =(int) fs.Length; byte[] data = new byte[fsLength]; br.Read(data, 0, fsLength); string str = Encoding.UTF8.GetString(data); System.Diagnostics.Debug.WriteLine(str); } } } static void SaveData(Stream sm) { var bw = new BinaryWriter(sm); for(int i=0;i<10000;i++) { string msg = $"Time {DateTime.Now.ToString("yyyyMMddHHmmssffff")},Guid {Guid.NewGuid()}\n"; bw.Write(msg); } bw.Flush(); } static void LoadData(Stream sm) { var br = new BinaryReader(sm); int smLength = (int)sm.Length; byte[] byteArr = new byte[smLength]; br.Read(byteArr, 0, smLength); string str = Encoding.UTF8.GetString(byteArr); Console.WriteLine(str); }
赞 (0)