使用C#将PDF保存到SQL数据库时截断字节数组

时间:2017-01-29 22:18:12

标签: c# sql sql-server

我有一个应用程序将PDF文件保存在本地SQL数据库中供以后检索,我遇到的问题是文件没有正确保存到数据库,并且在检索时我的所有文件都只是79个字节。

以下是保存它的代码:

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);
}

让我知道我做错了什么......

0 个答案:

没有答案