C# 操作数据库写入、读取二进制文件

dream__life 2008-09-16 03:24:51
protected void Button1_Click(object sender, EventArgs e)
{
//写入
string path = this.FileUpload1.PostedFile.FileName;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);

int length = this.FileUpload1.PostedFile.ContentLength;
byte[] wordData = new byte[length];
stream.Read(wordData, 0, length);
stream.Close();

SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("insert into word values('test','" + wordData + "')", con);
cmd.ExecuteNonQuery();
con.Close();

}

protected void Button2_Click(object sender, EventArgs e)
{
//读取
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select content from word where id=9", con);
SqlDataReader sdr = cmd.ExecuteReader();

FileStream fs;
BinaryWriter bw;

byte[] outbyte = null;

string filePath = @"D:\word.doc";

while (sdr.Read())
{
fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
bw = new BinaryWriter(fs);

outbyte=(byte[])sdr["content"];
bw.Write(outbyte, 0, outbyte.Length);

bw.Flush();
bw.Close();
fs.Close();
}
sdr.Close();
con.Close();
}


我用来将WORD文档写入数据库,再读取到指定目录下。
但是无法读取出来,程序运行后,打开文档,内容只有“System.Byte[]”。
在线等,我要疯了……
...全文
303 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dream__life 2008-09-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 songhuan 的回复:]
这有错误
SqlCommand cmd = new SqlCommand("insert into word values('test','" + wordData + "')", con);


改成这样

SqlCommand cmd = new SqlCommand("insert into word values('test',@wordData )", con);
cmd.Parameters.Add("@wordData ", wordData )
[/Quote]

Thank You!!! OK了!
不过存入的英文文档可以正常读取,但是中文的WORD文档,读取出来之后就是乱码了……
郁闷中
dream__life 2008-09-16
  • 打赏
  • 举报
回复
不行啊,生成的WORD中只有“System.Byte[]”这个内容。
songhuan 2008-09-16
  • 打赏
  • 举报
回复
这有错误
SqlCommand cmd = new SqlCommand("insert into word values('test','" + wordData + "')", con);


改成这样

SqlCommand cmd = new SqlCommand("insert into word values('test',@wordData )", con);
cmd.Parameters.Add("@wordData ", wordData )
cpio 2008-09-16
  • 打赏
  • 举报
回复
string path = this.FileUpload1.PostedFile.FileName;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);

你要知道FileUpload1.PostedFile.FileName表示用户的文件路径

FileUpload1.PostedFile.InputStream,或者FileUpload1.FileContent 表示内容(Stream)

也可以直接用FileUpload1.FileBytes
jackyoung02 2008-09-16
  • 打赏
  • 举报
回复
是这句有问题:

byte[] outbyte = null;

改成如下试试看:


byte[] outbyte = new byte[(int)sdr["content"].ToString().Length];

62,242

社区成员

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

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

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

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