gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:56:55 26 4
gpt4 key购买 nike

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

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

关于c# - 从数据库反序列化二进制数组 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37554254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com