I am having some trouble downloading a file from the file path saved in my SQL Server database.
The file is saved in my database as \\server\Exec\C_Exec.pdf
so now I am trying to download that file.
The code I have so far is:
Select the id of the file you want to download:
protected void ContactsGridViewExec_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ExecCommand"))
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
var val = this.ExecGridView.DataKeys[rowIndex]["id"];
string strQuery = "SELECT filename, filecontent, datestamp FROM FileTable WHERE id=@id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = val;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
}
Then download the file:
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["filecontent"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["filename"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
This code throws an exception
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Byte[]'.'
When I remove this line
Byte[] bytes = (Byte[])dt.Rows[0]["filecontent"];
and
Response.BinaryWrite(bytes);
It then downloads the file but there are no information or can't open the file (in this case a PDF).