C# Code Snippet - Convert file to byte array

C# Code Snippet - Convert file to byte array

C# Code Snippet - Convert file to byte array

(C-Sharp) C# code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting.

Bookmark:

C# Code Snippet - Convert file to byte array

This .Net C# code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting. To use this function simply provide file path to external file. This function uses System.IO name space to open file using FileStream and reading from BinaryReader. Modify the exception handling section to as your project requirements.

/// <summary>
/// Function to get byte array from a file
/// </summary>
/// <param name="_FileName">File name to get byte array</param>
/// <returns>Byte Array</returns>
public byte[] FileToByteArray(string _FileName)
{
    byte[] _Buffer = null;

    try
    {
        // Open file for reading
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        
        // attach filestream to binary reader
        System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
        
        // get total byte length of the file
        long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
        
        // read entire file into buffer
        _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
        
        // close file reader
        _FileStream.Close();
        _FileStream.Dispose();
        _BinaryReader.Close();
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    return _Buffer;
}


Here is a simple example showing how to use above function (FileToByteArray) load external image in a file to byte array and show it in a picturebox (this is just to demonstrate this function, there are other methods to load image in picturebox).

System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(FileToByteArray("C:\\sample-image.jpg"));
pictureBox1.Image = System.Drawing.Image.FromStream(_MemoryStream);


Here is a simple example showing how to use above function (FileToByteArray) to store image in sql server database. This example shows how to read external file and convert it into byte array and then insert binary data into SQL server as a new record using sql parameter.

// set temporary variable for database connection
System.Data.SqlClient.SqlConnection _SqlConnection = new System.Data.SqlClient.SqlConnection();

// assign database connection string
_SqlConnection.ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;";

// Connect to database
try
{
    // open database connection
    _SqlConnection.Open();

    // Set SQL statement to insert new record to database
    string _SQL = "INSERT INTO sampletable (name, price, image) VALUES ('sample product name', 22.75, @image)";
    
    // lets add this record to database
    System.Data.SqlClient.SqlCommand _SqlCommand
        = new System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection);

    // Add image as SQL parameter
    System.Data.SqlClient.SqlParameter _SqlParameter
        = new System.Data.SqlClient.SqlParameter("@image", SqlDbType.Image);

    // convert image file to byte array and pass to sql parameter value
    _SqlParameter.Value = FileToByteArray("C:\\sample-image.jpg");
    _SqlCommand.Parameters.Add(_SqlParameter);

    // Executes a Transact-SQL statement against the connection 
    _SqlCommand.ExecuteNonQuery();

    // Dispose command
    _SqlCommand.Dispose();
    _SqlCommand = null;

}
catch (Exception _Exception)
{
    // Error
    Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}

// close database connection
_SqlConnection.Close();


C# Keywords Used:

  • FileStream
  • BinaryReader
  • FileInfo
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, SQL, FileStream, BinaryReader, FileMode, File to byte array, Remoting, Store binary in database, SQL Server Binary Data
  • Programming Language : C# (C-Sharp)

External Resources:

sa :: November 26-2009 :: 05:34 AM

hi this is great

vikas :: March 12-2010 :: 05:46 AM

what is the solution for creating the crystal report from the database in which we inserted that image in binary format and now in crystal report  having that field in image format

Spyke Krepshaw :: May 26-2010 :: 09:47 AM

Hi, I am using the function above and am getting binary data inside my DB but it will not show the image in a web browser at all.

ateendra :: July 28-2010 :: 09:13 AM

hi, can you give me an equivalent code in c++

dushantha maduranga :: August 02-2010 :: 07:42 AM

i have created an application to upload files to sever and it is successfull now. But i need to download them exactly the format they have uploaded.(eg .doc/.pdf/.ppt/) 

paramesh :: September 10-2010 :: 03:20 AM

hai this is grt........i need coding for convert image into byte ,then store into sql db,then display image into grid view(convert bytecode into image)....

Nitin :: April 09-2011 :: 01:51 PM

Hi, Need a favor, actually i am using Binaryreader in vb.net to read any file, and get first 4-bytes values from the file(external) using GUI (FileOpenDialog) now , i need to get the 4-bytes value from the above and match or compare that with the values in my MS SQL database. which already will have 4-byte values for that file. how to write the vb.net code and Sql code for that? Please help Thanks in advance

priyanka :: June 30-2011 :: 08:08 AM

Hi, Great work! I need a code snippet for multi-part upload. Can anyone pls help!

Leave a comment