I have an application that saves a PDF file in a local SQL database for later retrieval, the problem I'm experiencing is that somehow the file is not being saved to the database correctly, and upon retrieval all of my files are only 79 bytes.
Here's the code that saves it:
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();
}
}
I also tried a different way of converting it into a byte array:
byte[] addingFile;
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
addingFile = reader.ReadBytes((int)stream.Length);
}
}
And then this is how I'm retrieving it:
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);
}
Let me know what I'm doing wrong...