Denis Denis - 13 days ago 6
C# Question

How to read int array from binary file c#

I have the following code:

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


How to read array elements from the file? I tried several ways. For example, I wrote the length of the array to the file, and I tried to read the number. However, I had failed.

Note. I need to get the int array.

bas bas
Answer

Are you looking for this:

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

Or more something like:

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

Or, a small example with unit tests:

Create a binary file with integers...

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

And a small example test of reading from a binary file

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

Another approach of reading from binary file

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