簡體   English   中英

如何從二進制文件C#中讀取整數數組

[英]How to read int array from binary file c#

我有以下代碼:

LZW lzw = new LZW();
int[] a = lzw.Encode(imageBytes);

FileStream fs = new FileStream("image-text-16.txt", FileMode.Append);
BinaryWriter w = new BinaryWriter(fs);

for (int i = 0; i < a.Length; i++)
{
   w.Write(a[i]);

}

w.Close();
fs.Close();

如何從文件中讀取數組元素? 我嘗試了幾種方法。 例如,我將數組的長度寫入文件,然后嘗試讀取該數字。 但是,我失敗了。

注意。 我需要獲取int數組。

您在尋找這個嗎?

var bytes = File.ReadAllBytes(@"yourpathtofile");

或更多類似的東西:

        using (var filestream = File.Open(@"C:\apps\test.txt", FileMode.Open))
        using (var binaryStream = new BinaryReader(filestream))
        {
            for (var i = 0; i < arraysize; i++)
            {
                Console.WriteLine(binaryStream.ReadInt32());
            }
        }

或者,一個帶有單元測試的小例子:

創建一個帶有整數的二進制文件...

    [Test]
    public void WriteToBinaryFile()
    {
        var ints = new[] {1, 2, 3, 4, 5, 6, 7};

        using (var filestream = File.Create(@"c:\apps\test.bin"))
        using (var binarystream = new BinaryWriter(filestream))
        {
            foreach (var i in ints)
            {
                binarystream.Write(i);
            }
        }
    }

還有一個讀取二進制文件的小示例測試

    [Test]
    public void ReadFromBinaryFile()
    {
        // Approach one
        using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
        using (var binaryStream = new BinaryReader(filestream))
        {
            var pos = 0;
            var length = (int)binaryStream.BaseStream.Length;
            while (pos < length)
            {
                var integerFromFile = binaryStream.ReadInt32();
                pos += sizeof(int);
            }
        }
    }

從二進制文件讀取的另一種方法

    [Test]
    public void ReadFromBinaryFile2()
    {
        // Approach two
        using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
        using (var binaryStream = new BinaryReader(filestream))
        {
            while (binaryStream.PeekChar() != -1)
            {
                var integerFromFile = binaryStream.ReadInt32();
            }
        }
    }

我會反過來說。 唯一的事情是您在閱讀尺寸之前不知道尺寸,因此請先進行計算。 哦,我會使用“使用”來確保正確處置(並關閉)物件:

        int[] ll;
        using (FileStream fs = File.OpenRead("image-text-16.txt"))
        {
            int numberEntries = fs.Length / sizeof(int);
            using (BinaryReader br = new BinaryReader(fs))
            {
                ll = new int[numberEntries];
                for (int i = 0; i < numberEntries; ++i)
                {
                    ll[i] = br.ReadInt32();
                }
            }
        }
        // ll is the result

我不太了解的是為什么要從LZW編寫int [],但是我想這是有原因的...

暫無
暫無

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

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