Read byte array from file in CSharp

Description

The following code shows how to read byte array from file.

Example


//  ww w. j a v  a2  s. c om
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

public class FileUtils
{
        public static void Main(String[] argv){
            Console.WriteLine(GetFileBytes("test.txt").Length);
        }
        
        public static byte[] GetFileBytes(string filename)
        {
           if (File.Exists(filename))
            {
                FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read);

                byte[] fileBytes = new byte[fs.Length];

                fs.Read(fileBytes, 0, (int)fs.Length);

                fs.Close();

                return fileBytes;
            }

            return null;
        }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var