1.写入二进制文件: ①用到的命名空间: using System.IO; using System.Text; ②写进二进制文件: public Stream s; public BinaryWriter w; s = File.Create("test.bin"); w = new BinaryWriter(s);//基于所提供的流,用 UTF-8 作为字符串编码来初始化 BinaryWriter 类的新实例。 string str = "这是一行文字。/n"; w.Write(str); float a = 3.1415F; w.Write(a); ulong b = 100000L; w.Write(b); int c = 300; w.Write(c); decimal d = 4.40983M; w.Write(d); double f = 94853.938485928d; w.Write(f); char[] g = {'h','e','l','l','o'}; w.Write(g, 0, g.Length); char h = 'W'; w.Write(h); bool i = true; w.Write(i); w.Flush();//清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。 w.Close();//关闭当前的 BinaryWriter 和基础流。 2.读取二进制文件: ①用到的命名空间: using System.IO; using System.Text; ②读二进制文件: public Stream s; public BinaryReader r; // 显示二进制文件内容 private void button1_Click(object sender, System.EventArgs e) { s = File.OpenRead("test.bin"); r = new BinaryReader(s); richTextBox1.Text = "显示 String:"; richTextBox1.Text += r.ReadString(); richTextBox1.Text += "显示 Float:"; richTextBox1.Text += r.ReadSingle().ToString() + "/n"; richTextBox1.Text += "显示 ULong:"; richTextBox1.Text += r.ReadUInt64().ToString() + "/n"; richTextBox1.Text += "显示 Int:"; richTextBox1.Text += r.ReadInt32().ToString() + "/n"; richTextBox1.Text += "显示 Decimal:"; richTextBox1.Text += r.ReadDecimal().ToString() + "/n"; richTextBox1.Text += "显示 Double:"; richTextBox1.Text += r.ReadDouble().ToString() + "/n"; richTextBox1.Text += "显示 Char[]:"; richTextBox1.Text += Encoding.ASCII.GetString(r.ReadBytes(5)) + "/n"; richTextBox1.Text += "显示 Char:"; richTextBox1.Text += r.ReadChar().ToString() + "/n"; richTextBox1.Text += "显示 Boolean:"; richTextBox1.Text += r.ReadBoolean().ToString() + "/n"; r.Close(); }