簡體   English   中英

從數據庫C#反序列化二進制數組

[英]Deserialize binary array from database C#

我正在嘗試在數據庫中保存和檢索文件。 我正在序列化對象並將其保存為二進制。 但是,當嘗試反序列化時,出現錯誤,即輸入流不是有效的二進制格式。 我嘗試了幾種解決方案,到目前為止,這是我整理的內容:

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

這是負載

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;

    }

這是我將二進制數據插入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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM