0

I am saving Image in a database in a wpf App. but when i retrieve it it gives me type cast error.

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

i am using following code to type cast

byte[] data = (byte[])ds.Tables[0].Rows[0]["ProjectIcons"];
EagleBeak
  • 6,939
  • 8
  • 31
  • 47
Harjeet Singh
  • 388
  • 2
  • 6
  • 22
  • What's the type of your "ProjectIcons" in the database? – HABJAN Jun 06 '14 at 12:06
  • 1
    Well presumably the type of the `ProjectItems` column is `String` instead of `byte[]`... Either your database is using the wrong column type, or you're using the wrong type when fetching it. We need more context. – Jon Skeet Jun 06 '14 at 12:06
  • @HABJAN varBinary(max) – Harjeet Singh Jun 06 '14 at 12:06
  • @HarjeetSingh: take a look at this: http://stackoverflow.com/questions/4900605/sql-server-varbinarymax-to-c-sharp-byte – HABJAN Jun 06 '14 at 12:09

2 Answers2

1

In order to convert from string to byte[], you need to specify the encoding. Using UTF-8, it'd be:

byte [] stringArray = Encoding.UTF8.GetBytes("aaa");

Keep in mind that the same character may be represented by different number and value of bytes, so depending on what you need it for, you'll have to use the right encoding.

  • Thanks @Caótico fanegas , How may i check the format? means coded format , so i will encode it – Harjeet Singh Jun 06 '14 at 12:46
  • Somehow, @HarjeetSingh, `ds.Tables[0].Rows[0]["ProjectIcons"]`is returning a string, use the Visual Studio Inspector and breakpoints to consult the actual type and value of that datatable field. Also, what's the database type of that field? – Caótico fanegas Jun 06 '14 at 12:50
  • i inspect it. it has System.Byte[] in its Value and Object{string} in its Type. Datatype in db is varBinary(max) , i also tried with Type image – Harjeet Singh Jun 06 '14 at 12:59
0

Try this

string s = (string)ds.Tables[0].Rows[0]["ProjectIcons"];
byte[] data = System.Text.Encoding.ASCII.GetBytes(s);
Systematix Infotech
  • 2,345
  • 1
  • 14
  • 31