C++/CLI Code Snippet - Save byte array to file

C++/CLI Code Snippet - Save byte array to file

C++/CLI Code Snippet - Save byte array to file

C++/CLI code snippet save byte array in to an external file. This function useful to store binary data in files. This function can be use when retrieving binary data from database and save it to an external file.

Bookmark:

C++/CLI Code Snippet - Save byte array to file

This .Net C++/CLI code snippet save byte array in to an external file. This function useful to store binary data in files. Function return true if byte array successfully written to file, else return false. Most common method to store binary data in database is as a byte array format. This function can be use when retrieving binary data from database and save it to an 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.

01bool ByteArrayToFile(System::String ^_FileName, array<System::Byte> ^_ByteArray)
02{
03    try
04    {
05        // Open file for writing
06        System::IO::FileStream ^_FileStream = gcnew System::IO::FileStream(_FileName, System::IO::FileMode::Create, System::IO::FileAccess::Write);
07 
08        // Writes a block of bytes to this stream using data from a byte array.
09        _FileStream->Write(_ByteArray, 0, _ByteArray->Length);
10 
11        // close file stream
12        _FileStream->Close();
13 
14        return true;
15    }
16    catch (Exception ^_Exception)
17    {
18        // Error
19        Console::WriteLine("Exception caught in process: {0}", _Exception->ToString());
20    }
21 
22    // error occured, return false
23    return false;
24}


Here is a simple example showing how to use above function (ByteArrayToFile). In this example we save byte array variable _ByteArray into a file byte-array.dat.

1array<System::Byte> ^_ByteArray = ..... some data .....;
2 
3ByteArrayToFile("c:\\image-object.dat", _ByteArray);


C++/CLI Keywords Used:

  • FileStream
  • FileAccess
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, SQL, Byte array to file, FileMode, FileAccess
  • Programming Language : C++/CLI

External Resources:

Leave a comment

 Poster Information 


(will not be published, required)

 MESSAGE DETAILS