我创建了一个数据库(带VS向导),其中包含2列: Id,fData ;; fData类型是nvarchar(MAX)。 然后我用这个命令插入一个文件:
public void InsertToDB()
{
byte[] data = File.ReadAllBytes(barcodeEXE); //this is an exe file
string base64 = Convert.ToBase64String(data);
mytbl3TableAdapter.Insert(1, base64);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
//FILE ADDED !
}
现在每件事都没问题(文件以base64string格式添加到数据库中,我们不需要再使用这些命令来插入文件)问题在这里:我将数据从数据库复制到其他使用此命令的文件夹:
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
string base64;
base64 = ((string)mydb3DataSet.Tables[0].Rows[0]["fData"]);
byte[] base64byte = Convert.FromBase64String(base64);
mytbl3TableAdapter.Update(mydb3DataSet.mytbl3);
mytbl3TableAdapter.Fill(mydb3DataSet.mytbl3);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
d.Close();
//
}
d.Close();
}
//end
con.Close();
}
文件将成功复制,但数据将从数据库中删除!!
答案 0 :(得分:0)
CopyFromDB函数看起来没有按照您的意图执行:
public void CopyFromDB()
{
con = new SqlConnection();
con.ConnectionString = CnString;
con.Open(); //start
SqlCommand cmd = new SqlCommand("SELECT fData FROM [mytbl3] WHERE Id=1", con);
using (SqlDataReader d = cmd.ExecuteReader())
{
if (d.Read())
{
string base64;
base64 = reader.GetString(d.GetOrdinal("fData"));
byte[] base64byte = Convert.FromBase64String(base64);
SaveFileDialog ofd = new SaveFileDialog(); ofd.Filter = "exe file|*.exe";
if (ofd.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(ofd.FileName, base64byte);
System.Threading.Thread.Sleep(3000);
}
}
d.Close();
//end
con.Close();
}
}