Write a binary file
-10
Write a set of bytes into a so-called binary file. The point is that we use BinaryWriter here and we have a byte array as input.
/// <summary>
/// Write a binary file
/// </summary>
/// <param name="filePath">Complete path to the file to be written</param>
/// <returns>True, if file was correctly saved.</returns>
public bool WriteBinaryFile(string filePath, byte[] contents)
{
bool okok = true; // ok, file written
FileStream fs = null;
BinaryWriter w = null;
try
{
fs = new FileStream(filePath, FileMode.CreateNew);
w = new BinaryWriter(fs);
w.Write(contents);
}
catch (IOException e)
{
okok = false; // houston, we have a problem
}
finally
{
if (w!=null)
w.Close();
if (fs!=null)
fs.Close();
}
return okok;
}






A better example...
Bobby R Ward
---------------------
bobbyrward@gmail.com
/// <summary>
/// Write binary to a stream
/// </summary>
/// <param name="stream">The System.IO.Stream based object to write to</param>
public void WriteBinaryStream(System.IO.Stream stream, byte[] contents)
{
using(System.IO.BinaryWriter w = new System.IO.BinaryWriter(stream))
w.Write(contents);
}
/// <summary>
/// Write binary to a file
/// </summary>
/// <param name="stream">The System.IO.Stream based object to write to</param>
public void WriteBinaryFile(string filename, byte[] contents)
{
using(System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
WriteBinaryStream(fs, contents);
}