簡體   English   中英

將多字節[]寫入和讀取到文件C#

[英]Write and read the multiple byte[] into the file C#

我想將三個字節的 arrays 寫入文件中。 而且,稍后我需要以同樣的方式閱讀。 C# 有可能嗎? 考慮下面的例子,

byte[] source = new byte[0];
byte[] delim = new byte[0];
byte[] dest = new byte[0];

所以,現在我打算把這三個字節的 arrays 和單個文件一起寫,如下所示,

byte[] writeData = new byte[source.Length + delim.Length + dest.Length];
Buffer.BlockCopy(source, 0, writeData, 0, source.Length);
Buffer.BlockCopy(delim, 0, writeData, source.Length, delim.Length);
Buffer.BlockCopy(dest, 0, writeData, source.Length + delim.Length, dest.Length);

File.WriteAllBytes("myfile.txt", writeData);

一段時間后,我想讀取文件並根據 delim 拆分源和目標字節數組。 可能嗎?。 如果是,我怎么能做到這一點? 任何示例代碼將不勝感激。

在此先感謝您的幫助。

您可以使用BinaryWriterBinaryReader ,如下所示。 首先將數組的長度寫入 int32,然后寫入數組字節。 對第二個數組重復。 相反,將數組的長度讀取為 int32,然后讀取那么多字節。 對第二個數組重復:

byte[] source = new byte[2] { 1, 2 };
byte[] dest = new byte[6] { 2, 4, 8, 16, 32, 64 };

using (FileStream fs = new FileStream("myFile.txt", FileMode.OpenOrCreate))
{
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
        bw.Write(source.Length);
        bw.Write(source, 0, source.Length);
        bw.Write(dest.Length);                    
        bw.Write(dest, 0, dest.Length);
    }                
}

byte[] source2;
byte[] dest2;
using (FileStream fs = new FileStream("myFile.txt", FileMode.Open))
{
    using (BinaryReader br = new BinaryReader(fs))
    {
        source2 = br.ReadBytes(br.ReadInt32());
        dest2 = br.ReadBytes(br.ReadInt32());
    }
}

Console.WriteLine("source = " + String.Join(" ", source));
Console.WriteLine("dest = " + String.Join(" ", dest));
Console.WriteLine("source2 = " + String.Join(" ", source2));
Console.WriteLine("dest2 = " + String.Join(" ", dest2));

Output:

source = 1 2
dest = 2 4 8 16 32 64
source2 = 1 2
dest2 = 2 4 8 16 32 64

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM