简体   繁体   中英

Deserialize binary array from database C#

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;

    }

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM