How to write Byte[] Array to a file in C#

1 Answer

0 votes
using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        
        static void Main(string[] args)
        {
            try
            {
                byte[] barr = null;

                ReadBinaryFile("d:\\image.gif", 0, 13, ref barr);
                File.WriteAllBytes("d:\\byte.bin", barr); // write Byte[] Array to file
            }
            catch (IOException ioex)
            {
                Console.WriteLine(ioex.Message);
            }
        }
        static void ReadBinaryFile(string file, int start, int len, ref byte[] barr)
        {
            using (BinaryReader br = new BinaryReader(File.Open(file, FileMode.Open)))
            {
                int total_len = (int)br.BaseStream.Length, pos = 0;

                if (start >= 0)
                    pos += start;
                else
                    pos = total_len - Math.Abs(start);
                    
                len = pos + len;
                if (len > total_len) return;

                br.BaseStream.Seek(pos, SeekOrigin.Begin);
                int i = 0;
                barr = new byte[len - pos];
                while (pos++ < len)
                    barr[i++] = br.ReadByte();
            }
        }
    }
}

/*
run:
   
byte.bin
--------
GIF89a 
 p  

*/


answered Mar 17, 2015 by avibootz
edited Mar 17, 2015 by avibootz

Related questions

...