C#對二進位檔案的特定位置進行讀寫小結

來源:互聯網
上載者:User

標籤:c#   nbsp   origin   修改   輸出   point   substr   參數   desktop   

雖然網路上對“C#對二進位檔案進行讀寫”的文章如汗牛充棟,但具體到自己要處理的問題時,難免讓人產生“書到用時方恨少”和“紙上讀來終覺淺”的感覺,最終理解還是要靠自己動手才能豐衣足食。 

 

執行個體一:將數值寫入檔案的特定位置

    String saveFile = "C:\\Users\\ufo\\Desktop\\rich4\\SAVE2.DAT";// 要儲存的檔案    FileStream writeStream = File.OpenWrite(saveFile);// 以寫的方式開啟    int value = 123456;// 要寫入的數值    String strAll = value.ToString("x8");// 轉成16進位
// 下面是特定處理,個人化需求,不完善勿怪 String strA = strAll.Substring(strAll.Length - 2, 2); String strB = strAll.Substring(strAll.Length - 4, 2); String strC = strAll.Substring(strAll.Length - 6, 2); byte[] newData = new byte[3]; newData[0] = Convert.ToByte(strA, 16); newData[1] = Convert.ToByte(strB, 16); newData[2] = Convert.ToByte(strC, 16); writeStream.Seek(44, SeekOrigin.Begin);// 定位,在第44個位元組處寫入 writeStream.Write(newData, 0, newData.Length);// 將準備好的數組寫入檔案。newData是包含要寫入檔案的byte類型數組;0是數組中的從零開始的位元組位移量,從此處開始將位元組複製到該流;newData.Length是要寫入的位元組數。這句話的意思是從44個位元組開始把數組內容從頭到尾寫進去,修改下參數如writeStream.Write(newData, 1, newData.Length-1)是把數組從第二個到倒數第一個寫進去
    writeStream.Close();// 關閉檔案

 

執行個體二:讀取檔案的特定位置,得到數值

    String openFile = "C:\\Users\\ufo\\Desktop\\rich4\\SAVE2.DAT";// 要讀取的檔案    FileStream fs = new FileStream(openFile, FileMode.Open);// 讀取方式開啟,得到流    fs.Seek(44, SeekOrigin.Begin);// 定位到第44個位元組    byte[] datas = new byte[3];// 要讀取的內容會放到這個數組裡    fs.Read(datas, 0, datas.Length);// 開始讀取,讀取的內容放到datas數組裡,0是從第一個開始放,datas.length是最多允許放多少個
  // 下面是個人化處理,不完善勿怪 int a = datas[2]; String strA = Convert.ToString(a, 16); if (strA.Equals("")) { strA = "00"; } if (strA.Length == 1) { strA = "0" + strA; } a = datas[1]; String strB = Convert.ToString(a, 16); if (strB.Equals("")) { strB = "00"; } if (strB.Length == 1) { strB = "0" + strB; } a = datas[0]; String strC = Convert.ToString(a, 16); if (strC.Equals("")) { strC = "00"; } if (strC.Length == 1) { strC = "0" + strC; } String strD = strA + strB + strC; int point = Convert.ToInt32(strD, 16);// 十六進位轉十進位 System.Console.WriteLine("value=" + point);// 這裡輸出value=123456,也就是上面寫入程式寫進去的值

 

2017年6月13日11:43:46

C#對二進位檔案的特定位置進行讀寫小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.