简体   繁体   中英

How to retrieve byte array from database in C#?

I am trying to get a byte array from varBinary(max) column of a table:-

    SqlDataAdapter sda=new SqlDataAdapter("select * from mine", sqlconn);
    DataTable dt=new DataTable();
    sda.Fill(dt);
    string fileName=dt.Rows[0][0].ToString();
    byte[] file = (byte[])dt.Rows[0][1];

But I get an exception: Unable to cast object of type 'System.String' to type 'System.Byte[]'.

I am not sure what Encoding you have used,but if you want to Convert a String to byte Array,then

byte[] File=System.Text.UTF8Encoding.ASCII.GetBytes(fileName); /**Customized Encoding**/

and by Default .NET uses UTF16,so to use that

byte[] File = System.Text.Encoding.Unicode.GetBytes(fileName); /**Default Encoding**/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM