1. 程式人生 > 實用技巧 >C#(99):二進位制讀寫 BinaryReader、BinaryWriter、BinaryFormatter

C#(99):二進位制讀寫 BinaryReader、BinaryWriter、BinaryFormatter

一、二進位制讀寫類:

1、BinaryReader/BinaryWriter:二進位制讀寫

  • BinaryReader:用特定的編碼將基元資料型別讀作二進位制值。
  • BinaryWriter:以二進位制形式將基元型別寫入流,並支援用特定的編碼寫入字串。

2、XmlReader/XmlWriter :XML讀寫

見:https://www.cnblogs.com/springsnow/p/9428695.html

二、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.cnblogs.com/springsnow/p/9469399.html

2、舉例:

[Serializable]
public class Product //實體類
{
    public long Id;
    [NonSerialized]//標識不序列化此成員Name
    public string Name;
    public Product(long Id, string Name)
    {
        this.Id = Id;
        this.Name = Name;
    }
}

static void Main()
{
    //序列化(物件儲存到檔案)
    List<Product> Products = new List<Product> {
        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<Product> addresses = (List<Product>)formatter1.Deserialize(fs1);
    fs1.Close();
    foreach (Product de in addresses)
    {
        Console.WriteLine("{0} lives at {1}.", de.Id, de.Name);
    }
}