【发布时间】:2016-09-29 23:18:23
【问题描述】:
我正在尝试在数据库中保存和检索文件。我正在序列化对象并将其保存为二进制文件。但是,当尝试反序列化时,我收到输入流不是有效的二进制格式的错误。我尝试了几种解决方案,这是我到目前为止所总结的:
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;
}
【问题讨论】:
-
我没有使用图片。我正在序列化一个 TrafficMonitor 类型的对象。
-
您是否尝试过使用编码将字节数组转换为字符串(在保存到数据库之前),然后使用相同的编码将数据库字符串转换为字节数组。只是猜测 - stackoverflow.com/questions/11654562/…
-
对象被保存为二进制数组,我正在检索一个二进制数组,该数组必须放回对象中。我相信使用字符串会是一个额外的步骤。
-
File的数据类型是什么?
-
从 saveFile 中查看插入变量。它将是这样的:INSERT INTO user_files(FileName, Username, File) VALUES ('myfile','noname','System.Byte[]')。因此,您在反序列化时遇到问题
标签: c# mysql serialization binary deserialization