简体   繁体   English

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

[英]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: 这是我将二进制数据插入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: 以及如何从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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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