user3168680
user3168680

Reputation: 35

To retrieve image from oracle database by using imagepath in c#

Here is the code:

         MemoryStream memoryStream = new MemoryStream();

        string sql = "SELECT imgpath FROM imgemp WHERE empl_code = " + id + "";

        OracleCommand cmd = new OracleCommand(sql, connection);
        //cmd.Parameters.AddWithValue("@id", id);
        connection.Open();

        OracleDataReader reader = cmd.ExecuteReader();
        reader.Read();
        if (reader.HasRows)
        {
            //byte[] file = Encoding.ASCII.GetBytes("imgpath");
            //Get Image Data
            byte[] file = (byte[])reader["imgpath"];

            reader.Close();
            connection.Close();
            memoryStream.Write(file, 0, file.Length);
            context.Response.Buffer = true;
            context.Response.BinaryWrite(file);
            memoryStream.Dispose();

When I run it I am getting the following error,

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

Can anyone please help?

Upvotes: 2

Views: 766

Answers (2)

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

you need to read file's content not path into bytes array:

byte[] file = File.ReadAllBytes(reader["imgpath"].ToString());

Upvotes: 1

Ehsan
Ehsan

Reputation: 32681

By the name of your field it seems that you have stored path of file in the field imgpath and now you are trying to cast it to byte[]

Upvotes: 0

Related Questions