Click here to Skip to main content
16,013,918 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
// Read the file and convert it to Byte Array
        string filePath = Server.MapPath("APP_DATA/TestDoc.doc");
        string filename = Path.GetFileName(filePath);

        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);

protected void Retreive_Doc(object sender, EventArgs e)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }


private void download (DataTable dt)
    {
        //String[] strings=( String[])dt.Rows[0]["Data"];
        Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["ContentType"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename="
        + dt.Rows[0]["Name"].ToString());
        Response.BinaryWrite(bytes);
        Response.Flush(); 
        Response.End();
    }



i get this error

Unable to cast object of type 'System.String' to type 'System.Byte[]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Byte[]'.

it insert data to database and dosen't retrive it
Posted
Updated 18-Feb-12 1:10am

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900