如何从二进制文件c#中读取int数组

时间:2013-02-09 13:34:48

标签: c# bytearray binaryfiles

我有以下代码:

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数组。

2 个答案:

答案 0 :(得分:6)

你在找这个:

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();
            }
        }
    }

答案 1 :(得分:1)

我反过来说。唯一的问题是你在阅读之前不知道它的大小,所以先计算一下。哦,我使用&#39;使用&#39;确保事情妥善处理(和关闭):

        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 [],但我想这就是原因......