0

I am trying to save and retrieve a file to and from a database. I am serializing the object ans saving it as binary. However, when trying to deserialize I get the error that the input stream is not a valid binary format. I tried several solutions and this is what I've put together so far:

public void saveFile(string filename, string file, object o)
    {
        byte[] myFile;
        if (o != null)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, o);
                myFile= ms.ToArray();
            }
         String insert = "INSERT INTO user_files(FileName, Username, File) VALUES ('myfile','noname','"+ myFile + "')";
         MySqlCommand command = new MySqlCommand(insert, connection);

            try
            {
                connection.Open();
                command.ExecuteNonQuery();

            }
            catch
            {
                MessageBox.Show("Sorry, something went wrong");

            }
            finally
            { connection.Close(); }
            }

And here is the Load

public TrafficMonitor LoadFile(string user, string filename)
    {
        TrafficMonitor obj = null;
        byte[] myFile = null;
        DataTable dt = new DataTable();
        MySqlDataAdapter getCommand = new MySqlDataAdapter("Select File from user_files where Username='noname' and filename='myfile'" , connection);

        try
        {

            connection.Open();
            getCommand.Fill(dt);
            foreach (DataRow row in dt.Rows)
            {
                myFile= (byte[])row["File"];
            }
            MemoryStream memStream = new MemoryStream();
            BinaryFormatter binForm = new BinaryFormatter();
            memStream.Write(myFile, 0, myFile.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            obj = (TrafficMonitor)binForm.Deserialize(memStream);

        }
        catch { MessageBox.Show("Sorry, something went wrong"); }
        finally { connection.Close(); }
        return obj;

    }
MonicaS
  • 155
  • 1
  • 3
  • 18
  • I am not using an image. I am serializing an object of type TrafficMonitor. – MonicaS May 31 '16 at 19:48
  • Have you tried using a Encoding for converting your byte array to string (before saving to database) and then using same encoding for converting database string to byte array. Just a guess - http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string – vabii May 31 '16 at 20:07
  • The object is saved as a binary array and I am retrieving a binary array which has to be put back into an object. I believe using a string would be an extra step. – MonicaS May 31 '16 at 20:11
  • What is the datatype of File? – vabii May 31 '16 at 20:29
  • Look at your insert variable from saveFile. It will be something like this: INSERT INTO user_files(FileName, Username, File) VALUES ('myfile','noname',**'System.Byte[]'**). Because of it you have a problem in deserialization – Artavazd Balayan May 31 '16 at 20:54
  • myFile is already of type Byte[] and it has an object of type Byte[] assigned: myFile= ms.ToArray(); – MonicaS May 31 '16 at 21:01
  • The file is a TrafficMonitor object – MonicaS Jun 01 '16 at 07:41

1 Answers1

0

Here is how I inserted binary data to MySQL:

byte[] imgBuffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
MySqlCommand query = new MySqlCommand();
query.Connection = _connection;
query.CommandText = "INSERT INTO Photos(id,img) VALUES(?id,?img)";
var id = Guid.NewGuid();
query.Parameters.Add("?id", MySqlDbType.Binary).Value = id.ToByteArray();
query.Parameters.Add("?img", MySqlDbType.Blob).Value = imgBuffer;
query.ExecuteNonQuery();

And how I read binary data from MySQL:

MySqlCommand query = new MySqlCommand();
query.Connection = _connection;
query.CommandText = "SELECT * FROM Photos WHERE id=@ID";
query.Parameters.Add("@id", MySqlDbType.Binary).Value = guid.ToByteArray();

using (MySqlDataReader reader = query.ExecuteReader())
{
    if (reader.Read())
    {
        Guid id = reader.GetGuid(0);
        byte[] imgBuffer = (byte[])reader.GetValue(1);
    }
}
Artavazd Balayan
  • 2,353
  • 1
  • 16
  • 25