/// <summary>
/// 得到一个image字段的内容
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="fieldName">字段名(必须为image类型字段)</param>
/// <param name="condition">查询条件</param>
/// <returns>字段的所有内容</returns>
public static byte[] getImage(string tableName,string fieldName,string condition) 
{
byte[] b = null;
string strSql = "select " + fieldName + " from " + tableName + " where " + condition;
SqlConnection conn  = null;
try
{
conn = Connect.getConnection();
SqlCommand myCommand = new SqlCommand(strSql,conn);
SqlDataReader myReader = myCommand.ExecuteReader();
if (myReader.Read()) 
{
SqlBinary binary = myReader.GetSqlBinary(0);
if (!binary.IsNull) 
{
b = binary.Value;
}
}
myReader.Close();
}
catch(Exception ex)
{
Log.Write("",ex.Message + "  语句为: " + strSql,System.Diagnostics.EventLogEntryType.Error,1);
}
finally
{
conn.Close();
}
return b;
}
/// <summary>
/// 写入一个image字段
/// </summary>
/// <param name="b">要写入的二进制流</param>
/// <param name="tableName">表名</param>
/// <param name="fieldName">字段名</param>
/// <param name="condition">查询条件</param>
public static void setImage(byte[] b,string tableName,string fieldName,string condition) 
{
string strSql = "update " + tableName + " set " + fieldName + " = @imgdata where " + condition;
SqlConnection conn = null;
try
{
conn = Connect.getConnection();
SqlCommand myCommand = new SqlCommand(strSql,conn);
myCommand.Parameters.Add("@imgdata",SqlDbType.Image).Value = b;
myCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
Log.Write("",ex.Message + "  语句为: " + strSql,System.Diagnostics.EventLogEntryType.Error,1);
}
finally
{
conn.Close();
}
}看看是否对你有帮助。

解决方案 »

  1.   

    把字符串 转化成 byte[]:
    System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
    把byte[] 转化成字符串:
    System.Text.Encoding.GetEncoding("GB2312").GetString(b)
      

  2.   

    纠正一下System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
    --〉
    System.Text.Encoding.GetEncoding("GB2312").GetBytes(str,0,str.Length,b,0)
      

  3.   

    使用Convert.ToByte()函数将字符串转化为Byte[]下面是插入的代码:zipfile即为Byte[]SqlCommand addEmp = new SqlCommand("INSERT INTO table (imagefield) "+"Values(@imagefield)", Connection);addEmp.Parameters.Add("@imagefield",   SqlDbType.Image, zipfile.Length).Value = zipfile;