我将pdf文件保存在数据库中,从数据库下载后,我看到它的名称完全改为Code,你能解释一下为什么吗?以及如何解决此问题以获得相同的pdf文件名?这是代码:
插入
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
byte[] file;
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
file = reader.ReadBytes((int)stream.Length);
}
}
SqlConnection varConnection = new SqlConnection("Server=.\\sqlexpress;Database=badge;integrated security=yes");
varConnection.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO archive Values(@dat,@disponible,@fil)", varConnection))
{
sqlWrite.Parameters.Add("@dat", SqlDbType.Date).Value = DateTime.Today;
sqlWrite.Parameters.Add("@disponible", SqlDbType.VarChar, 20).Value = comboBox1.Text;
sqlWrite.Parameters.Add("@fil", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
varConnection.Close();
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
byte[] file;
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
file = reader.ReadBytes((int)stream.Length);
}
}
SqlConnection varConnection = new SqlConnection("Server=.\\sqlexpress;Database=badge;integrated security=yes");
varConnection.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO archive Values(@dat,@disponible,@fil)", varConnection))
{
sqlWrite.Parameters.Add("@dat", SqlDbType.Date).Value = DateTime.Today;
sqlWrite.Parameters.Add("@disponible", SqlDbType.VarChar, 20).Value = comboBox1.Text;
sqlWrite.Parameters.Add("@fil", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
varConnection.Close();
下载:
SqlConnection varConnection = new SqlConnection("Server=.\\sqlexpress;Database=badge;integrated security=yes");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select fil from archive where dat = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "' and disponible='"+comboBox1.Text+"'";
cmd.Connection = varConnection;
varConnection.Open();
SqlDataReader sqlRead = cmd.ExecuteReader();
SaveFileDialog svd = new SaveFileDialog();
svd.ShowDialog();
if (sqlRead.HasRows)
{
while (sqlRead.Read())
{
byte[] fileData = (byte[])sqlRead[0];
BinaryWriter fileCreate =
new BinaryWriter(File.Open(svd.FileName, FileMode.Create));
fileCreate.Write(fileData);
fileCreate.Close();
}
}
varConnection.Close();
答案 0 :(得分:1)
您似乎没有保存并获取原始文件名,而且您从SaveFileDialog
SaveFileDialog svd = new SaveFileDialog();
// ...
// svd.FileName is used, that is, user provided file name for the saved file
BinaryWriter fileCreate = new BinaryWriter(File.Open(svd.FileName, FileMode.Create));
您应该执行以下操作:
ofd.FileName
)cmd.CommandText = "select fil, filename from archive where dat = "
)P.S。您应该解决的代码还存在其他一些问题
SqlConnection
SqlCommand
和SqlDataReader
置于using
块cmd.CommandText = "select fil from archive where dat = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "' and disponible='"+comboBox1.Text+"'";
应该参数化,而不是通过字符串连接获得