2016-05-31 93 views
0

我試圖保存和檢索文件到數據庫和從數據庫檢索文件。我序列化對象並將其保存爲二進制文件。但是,當試圖反序列化時,我得到輸入流不是有效的二進制格式的錯誤。我嘗試了幾種解決方案,而這正是我已經把迄今:從數據庫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; 

    } 
+0

我沒有使用圖像。我正在序列化TrafficMonitor類型的對象。 – MonicaS

+0

您是否嘗試過使用編碼將字節數組轉換爲字符串(保存到數據庫之前),然後使用相同的編碼將數據庫字符串轉換爲字節數組。只是一個猜測 - http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string – vabii

+0

該對象被保存爲一個二進制數組,我正在檢索一個二進制數組,它必須放回到一個東西。我相信使用一個字符串將是一個額外的步驟。 – MonicaS

回答

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 [email protected]"; 
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); 
    } 
}