c# Bytes读写

来源:互联网 发布:淘宝卖假货会不会坐牢 编辑:程序博客网 时间:2024/05/29 15:29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReadAndWriteBytesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string _file = "d:\\test.dat";
            long data1 = 100;
            float data2 = 0.1F;
            byte[] _bytes;
            short _length;
            List<byte> _listBytes = new List<byte>();

            _length = 8;
            _bytes = BitConverter.GetBytes(_length);
            if(BitConverter.IsLittleEndian)
            {
                Array.Reverse(_bytes);
            }
            _listBytes.AddRange(_bytes);
            _bytes = BitConverter.GetBytes(data1);
            _listBytes.AddRange(_bytes);

            _length = 8;
            _bytes = BitConverter.GetBytes(_length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(_bytes);
            }
            _listBytes.AddRange(_bytes);
            _bytes = BitConverter.GetBytes(data2);
            _listBytes.AddRange(_bytes);

            System.IO.File.WriteAllBytes(_file, _listBytes.ToArray()); //写

            if (System.IO.File.Exists(_file))
            {
                _bytes = System.IO.File.ReadAllBytes(_file);//读
                int _index = 0;
                short _realdatal = BitConverter.ToInt16(_bytes, 0);
                _index += 2;

                long _realData1 = BitConverter.ToInt64(_bytes, _index);
                _index += 8;

                _realdatal = BitConverter.ToInt16(_bytes, _index);
                _index += 2;

                float _realData2 = BitConverter.ToSingle(_bytes, _index);
                _index += 8;

                Console.WriteLine(_realData1);
                Console.WriteLine(_realData2);
            }
        }
    }
}
原创粉丝点击