1.
fs.Position 写入的位置,从哪个位置开始写
fs.Write(byte1,0,byte1.Length); byte1写入的byte[], 写入内容从第几位开始取,length取多长。
数字转化成字节
short x = 6;
byte[] a=System.BitConverter.GetBytes(x); //得到小端字节序数组
Array.Reverse(a); //反转数组转成大端。
bin文件写入的显示是16进制。查看ASCII码表。
private void WriteFile() { string saveFileName = "d:\test.bin"; using (FileStream fs = new FileStream(saveFileName, FileMode.Create, FileAccess.Write)) { byte[] byte1 = System.Text.Encoding.ASCII.GetBytes("12345678"); fs.Position = 0; fs.Write(byte1, 0, byte1.Length); byte[] byte2 = System.Text.Encoding.ASCII.GetBytes("abcdef"); fs.Position = byte1.Length; fs.Write(byte2, 0, byte2.Length); byte[] byte3= System.Text.Encoding.ASCII.GetBytes("ABCDEF"); fs.Position = byte1.Length+ byte2.Length; fs.Write(byte3, 0, byte3.Length); }//end using }
读取
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); UInt32 imageSize = (UInt32)fs.Length; BinaryReader br = new BinaryReader(fs);