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