using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Drawing;
public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;User ID=sa;Password=123456");
            con.Open();
            SqlDataAdapter ada = new SqlDataAdapter("select * from tb14", con);
            DataSet ds = new DataSet();
            ada.Fill(ds);
            DropDownList1.DataSource = ds;
            DropDownList1.DataTextField = "id";
            DropDownList1.DataValueField = "id";
            DropDownList1.DataBind();
            Image1.Visible = false;
        }
    }    protected void Button1_Click(object sender, EventArgs e)
    {
        Image1.Visible = true;
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;User ID=sa;Password=123456");
        string imagename = "";
        try
        {
            con.Open();
            SqlCommand com = new SqlCommand("select * from tb14 where id=" + DropDownList1.Text + "", con);
            SqlDataReader dr = com.ExecuteReader();
            dr.Read();
            MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
            Bitmap image = new Bitmap(ms);
            string filepath = Server.MapPath("Img/");
            DirectoryInfo dir = new DirectoryInfo(filepath);
            FileInfo[] filecount = dir.GetFiles();
            int i = filecount.Length;
            imagename = filepath + ((i + 1) + ".jpg");
            image.Save(imagename);
            dr.Close();
            Image1.ImageUrl = "Img/" + ((i + 1) + ".jpg");
        }
        finally
        {
            con.Close();
        }
    }
}
显示的时候出现问题
无法将类型为“System.String”的对象强制转换为类型“System.Byte[]”。
请问改怎么解决

解决方案 »

  1.   

    MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
      

  2.   

     MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
    应该是这句报错了
      

  3.   

    大哥你至少也应该说一下哪句错了吧?
    http://wenwen.soso.com/z/q310788268.htm
    http://so.csdn.net/search?t=thread&q=%E6%97%A0%E6%B3%95%E5%B0%86%E7%B1%BB%E5%9E%8B%E4%B8%BA%E2%80%9CSystem.String%E2%80%9D%E7%9A%84%E5%AF%B9%E8%B1%A1%E5%BC%BA%E5%88%B6%E8%BD%AC%E6%8D%A2%E4%B8%BA%E7%B1%BB%E5%9E%8B%E2%80%9CSystem.Byte%5B%5D%E2%80%9D
      

  4.   

    dr["tName"]  数据类型不对应该是存储图片的字段,如果是文件路径则用FileStream(path)
      

  5.   

    MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
    额 我的疏忽 是这一句报错
    怎么改啊 
    sql中的图片名字改成 image类型的  怎么存进去啊
      

  6.   

    对应的数据字段是什么类型?
    要存image你得把图片先读到字节中(或者直接在上传的时候读进流里)
    http://www.cxybl.com/html/bcyy/net/201108222395.html