编程语言
首页 > 编程语言> > C# BinaryWriter BinaryReader demo

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);
        }

 

标签:int,fs,fsLength,C#,demo,FileStream,BinaryWriter,new,BinaryReader
来源: https://www.cnblogs.com/Fred1987/p/13049686.html