You must Sign In to post a response.
  • Category: ASP.NET

    Unable to cast object of type 'System.String' to type 'System.Byte[]'.

    Hi, Developers ,

    My code for load a attached file from database.

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    OleDbConnection con = Connection.DBconnection();
    OleDbCommand com = new OleDbCommand("select Name,type,data from WordFiles where id=@id", con);
    com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);
    OleDbDataReader dr = com.ExecuteReader();
    if (dr.Read())
    Response.Buffer = true;
    Response.ContentType = dr["type"].ToString();
    Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString()); // to open file prompt Box open or Save file
    Response.Charset = "";

    if i click the download link na it will be downloaded.but
    When i am try to download a attachment file it throws the following 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[]'.

    Source Error:

    Line 100: Response.Charset = "";
    Line 101: Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Line 102: Response.BinaryWrite((byte[])dr["data"]);
    Line 103: Response.End();
    Line 104: }

    So please help me to how i am resolve this error.

    Thanks with
  • #764406

    Some times back I had faced same issue.
    You have to encode the string from dr["data"] as below, so replace your code line Response.BinaryWrite((byte[])dr["data"]) with this code:

    byte[] bArrFileData = System.Text.Encoding.UTF8.GetBytes(dr["data"].ToString());
    byte[] bArrFileData = new byte[sizeof(char) * dr["data"].ToString().Length];
    //... copy no. of bytes to specified array
    System.Buffer.BlockCopy(dr["data"].ToString().ToCharArray(), 0, bArrFileData, 0, bArrFileData.Length);

    Hope it helps.
    Shashikant Gurav

  • #764407
    Heartful Thanks my brother Mr.Shashikant Gurav. Thanks a Lot.

    God bless you.

    I have this problem last 3 months.Now you are resolve it.

    thanks and Regards With

  • #764411

    Of course you cannot cast a string object into an array of bytes. 'Encoding.UTF8.GetBytes' method will help you to convert data to byteArray
    see below snippet
    byte[] b1 = System.Text.Encoding.UTF8.GetBytes (dr["data"].ToString());

    hope it helps

    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #764423
    Thavks mr.Prasad thanks for your reply


Sign In to post your comments