C# 使用C将PDF保存到SQL数据库时字节数组被截断#
我有一个应用程序,它将PDF文件保存在本地SQL数据库中,以便以后检索。我遇到的问题是,不知何故,该文件没有正确保存到数据库中,检索时,我所有的文件只有79字节 下面是保存它的代码:C# 使用C将PDF保存到SQL数据库时字节数组被截断#,c#,sql,sql-server,C#,Sql,Sql Server,我有一个应用程序,它将PDF文件保存在本地SQL数据库中,以便以后检索。我遇到的问题是,不知何故,该文件没有正确保存到数据库中,检索时,我所有的文件只有79字节 下面是保存它的代码: byte[] addingFile = System.IO.File.ReadAllBytes(file); using (SqlConnection varConnection = new SqlConnection() { ConnectionString = Properties.Settings.Defau
byte[] addingFile = System.IO.File.ReadAllBytes(file);
using (SqlConnection varConnection = new SqlConnection() { ConnectionString = Properties.Settings.Default.Database1ConnectionString })
{
varConnection.Open();
using (var sqlWrite = new SqlCommand("INSERT INTO Table1 (fileContent, fileName) Values(@File, @FileName)", varConnection))
{
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = addingFile;
sqlWrite.Parameters.AddWithValue("@FileName", file.Substring(lastSlash + 1, 7));
sqlWrite.ExecuteNonQuery();
}
}
我还尝试了另一种将其转换为字节数组的方法:
byte[] addingFile;
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
addingFile = reader.ReadBytes((int)stream.Length);
}
}
这就是我检索它的方式:
string tempPath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
label2.Text = tempPath;
com = new SqlCommand("select fileContent from Table1 where referenceID = " + "'" + scanInput.Text + "'", varConnection);
using (var sqlQueryResult = com.ExecuteReader())
if (sqlQueryResult != null)
{
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
using (var fs = new FileStream(tempPath, FileMode.Create, FileAccess.Write))
fs.Write(blob, 0, blob.Length);
}
让我知道我做错了什么…你写了
file.Length
而不是addingFile.Length
。你能发布你的表模式吗?@devio谢谢,这就解决了它!令人惊讶的是,我忽略了这一点,这就是我使用糟糕的命名约定所得到的。