我创建了一个数据库(使用 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();
}
文件将成功复制,但数据将从数据库中删除!!
最佳答案
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();
}
}
关于C# sql数据复制后会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654455/