首頁  >  文章  >  後端開發  >  使用 FileStream 類別讀取位元組數組並將其寫入檔案的 C# 程序

使用 FileStream 類別讀取位元組數組並將其寫入檔案的 C# 程序

WBOY
WBOY轉載
2023-08-29 16:21:041058瀏覽

使用 FileStream 类读取字节数组并将其写入文件的 C# 程序

C# 是一種強大的物件導向的程式語言,用於開發各種應用程式。在本文中,我們將討論如何使用 FileStream 類別編寫一個 C# 程序,將位元組數組讀取並寫入到檔案中。

第一步:建立一個位元組數組

該程式的第一步是建立一個我們想要寫入檔案的位元組數組。這是一個例子 -

byte[] byteArray = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 };

第 2 步:將位元組陣列寫入檔案

下一步是使用FileStream類別將位元組陣列寫入檔案。我們需要建立FileStream類別的新實例,並將檔案路徑、FileMode、FileAccess和FileShare作為參數傳遞給其建構函數。下面是一個範例 -

string filePath = "C:\MyFile.txt";
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) {
   fileStream.Write(byteArray, 0, byteArray.Length);
}

步驟3:從檔案讀取位元組陣列

要從檔案讀取位元組數組,我們需要建立 FileStream 類別的新實例,並將檔案路徑、FileMode、FileAccess 和 FileShare 作為參數傳遞給其建構子。然後,我們建立一個位元組數組,並使用 FileStream 類別的 Read() 方法將檔案的內容讀取到位元組數組中。這是一個例子 -

byte[] readByteArray = new byte[byteArray.Length];
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
   fileStream.Read(readByteArray, 0, readByteArray.Length);
}

第四步:比較位元組數組

最後,我們需要比較原始位元組數組和從檔案讀取的位元組數組,確保它們相同。我們可以使用 Enumerable 類別的 SequenceEqual() 方法來比較兩個位元組數組。這是一個例子 -

bool areEqual = byteArray.SequenceEqual(readByteArray);

範例

這是完整的 C# 程式 -

using System;
using System.IO;
using System.Linq;

namespace ByteArrayToFile {
   class Program {
      static void Main(string[] args) {
         byte[] byteArray = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 };
         string filePath = "C:\MyFile.txt";
         
         // Write byte array to file
         using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) {
            fileStream.Write(byteArray, 0, byteArray.Length);
         }
         
         // Read byte array from file
         byte[] readByteArray = new byte[byteArray.Length];
         using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
            fileStream.Read(readByteArray, 0, readByteArray.Length);
         }

         // Compare the byte arrays
         bool areEqual = byteArray.SequenceEqual(readByteArray);
         Console.WriteLine("Are the byte arrays equal? " + areEqual);
      }
   }
}

輸出

Are the byte arrays equal? True

結論

在本文中,我們學習如何使用FileStream類別編寫C#程式來讀取和寫入位元組陣列到檔案中。這個程式可以在各種場景中使用,例如讀取和寫入圖像或音訊檔案。透過理解本文涵蓋的概念,您可以開發出更高級的需要文件輸入和輸出的應用程式。希望本文對您的程式設計之旅有所幫助。愉快編碼!

以上是使用 FileStream 類別讀取位元組數組並將其寫入檔案的 C# 程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除