如何在C#中从数据库检索字节数组?
我试图从表的varBinary(max)列中获取字节数组:-如何在C#中从数据库检索字节数组?,c#,C#,我试图从表的varBinary(max)列中获取字节数组:- 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]; 但我遇到了
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];
但我遇到了一个例外:无法将“System.String”类型的对象强制转换为“System.Byte[]”类型。我不确定您使用了什么编码,但如果您想将字符串转换为字节数组,请
byte[] File=System.Text.UTF8Encoding.ASCII.GetBytes(fileName); /**Customized Encoding**/
默认情况下.NET使用UTF16,因此
byte[] File = System.Text.Encoding.Unicode.GetBytes(fileName); /**Default Encoding**/
System.Text.UTF8Encoding.ASCII.GetBytes(dt.Rows[0][1]);这听起来像是字符串类型的列,您的表定义是什么?