C#二进制读写BinaryReader、BinaryWriter、BinaryFormatter

一、二进制读写类: 1、BinaryReader/BinaryWriter:二进制读写

  • BinaryReader:用特定的编码将基元数据类型读作二进制值。
  • BinaryWriter:以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。
2、XmlReader/XmlWriter :XML读写
见:C#使?XmlReader和XmlWriter操作XML?件
二、BinaryReader/BinaryWriter 读写流的基元数据类型。可以操作图像、压缩文件等二进制文件。也可以是MemoryStream等。
不需要一个字节一个字节进行操作,可以是2个、4个、或8个字节这样操作。
可以将一个字符或数字按指定数量的字节进行写入。
1、写入:
using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create))){writer.Write(1.250F); writer.Write(@"c:\Temp"); writer.Write(10); writer.Write(true); }

Response.BinaryWrite()方法输出二进制图像
FileStream fs = new FileStream(Server.MapPath("未命名.jpg"), FileMode.Open); //将图片文件存在文件流中long fslength = fs.Length; //流长度byte[] b=new byte[(int)fslength]; //定义二进制数组fs.Read(b, 0, (int)fslength); //将流中字节写入二进制数组中fs.Close(); //关闭流Response.ContentType = "image/jpg"; //没有这个会出现乱码Response.BinaryWrite(b); //将图片输出在页面

2、读取:
每次读取都回提升流中的当前位置相应数量的字节。
下面的代码示例演示了如何存储和检索文件中的应用程序设置。
const string fileName = "AppSettings.dat"; float aspectRatio; string tempDirectory; int autoSaveTime; bool showStatusBar; if (File.Exists(fileName)){using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open))){aspectRatio = reader.ReadSingle(); tempDirectory = reader.ReadString(); autoSaveTime = reader.ReadInt32(); showStatusBar = reader.ReadBoolean(); }Console.WriteLine("Aspect ratio set to: " + aspectRatio); Console.WriteLine("Temp directory is: " + tempDirectory); Console.WriteLine("Auto save time set to: " + autoSaveTime); Console.WriteLine("Show status bar: " + showStatusBar); }

BinaryReader读取图片:
using (FileStream fs = new FileStream("1.jpg", FileMode.Open, FileAccess.Read)){//将图片以文件流的形式进行保存using (BinaryReader br = new BinaryReader(fs)){byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中br.Close(); }}

三、以二进制格式序列化对象BinaryFormatter 1、SoapFormatter(用于HTTP中)和BinaryFormatter(用于TCP中)类实现了IFormatter接口 (由继承IRemotingFormatter,支持远程过程调用 (Rpc))
  • Deserialize(Stream) 反序列化所提供流中的数据并重新组成对象图形。
  • Serialize(Stream, Object) 将对象或具有给定根的对象图形序列化为所提供的流。
XML序列化见:https://www.jb51.net/article/250477.htm
2、举例:
[Serializable]public class Product //实体类{public long Id; [NonSerialized]//标识不序列化此成员Namepublic string Name; public Product(long Id, string Name){this.Id = Id; this.Name = Name; }}static void Main(){//序列化(对象保存到文件)List Products = new List {new Product(1,"a"),new Product(2,"b")}; FileStream fs = new FileStream("DataFile.dat", FileMode.Create); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, Products); fs.Close(); //反序列化(文件内容转成对象)FileStream fs1 = new FileStream("DataFile.dat", FileMode.Open); BinaryFormatter formatter1 = new BinaryFormatter(); List addresses = (List)formatter1.Deserialize(fs1); fs1.Close(); foreach (Product de in addresses){Console.WriteLine("{0} lives at {1}.", de.Id, de.Name); }}

【C#二进制读写BinaryReader、BinaryWriter、BinaryFormatter】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读