从数据库C#反序列化二进制数组

时间:2016-05-31 19:37:34

标签: c# mysql serialization binary deserialization

我正在尝试在数据库中保存和检索文件。我正在序列化对象ans将其保存为二进制文件。但是,在尝试反序列化时,我得到输入流不是有效二进制格式的错误。我尝试了几种解决方案,这是我到目前为止所做的:

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

这是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;

    }

1 个答案:

答案 0 :(得分:0)

以下是我如何将二进制数据插入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();

我如何从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);
    }
}