无法将类型为“System.String”的对象强制转换为类型“System.Byte[]”。

panzhuanxin4 2011-11-17 09:48:36

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[]”。
请问改怎么解决
...全文
821 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
dr["tName"] 数据类型不对

应该是存储图片的字段,如果是文件路径则用FileStream(path)
赳赳老陈 2011-11-17
  • 打赏
  • 举报
回复
MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
应该是这句报错了
liukaizxc 2011-11-17
  • 打赏
  • 举报
回复
MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
  • 打赏
  • 举报
回复
对应的数据字段是什么类型?
要存image你得把图片先读到字节中(或者直接在上传的时候读进流里)
http://www.cxybl.com/html/bcyy/net/201108222395.html
panzhuanxin4 2011-11-17
  • 打赏
  • 举报
回复
MemoryStream ms = new MemoryStream((Byte[])dr["tName"]);
额 我的疏忽 是这一句报错
怎么改啊
sql中的图片名字改成 image类型的 怎么存进去啊

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧