C# 文件与二进制互转数据库写入读出
2024-08-30 01:17:14
//这个方法是浏览文件对象
private void button1_Click(object sender, EventArgs e)
{
//用户打开文件浏览
using (OpenFileDialog dialog = new OpenFileDialog())
{
//只能单选一个文件
dialog.Multiselect = false;
//选择一个文件
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
//把选择的文件路径给txtPath
this.textBox1.Text = dialog.FileName;
}
catch (Exception ex)
{
//抛出异常
throw (ex);
}
}
}
} //关闭
private void button3_Click(object sender, EventArgs e)
{
this.Close();
} //把文件转成二进制流出入数据库
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
Byte[] byData = br.ReadBytes((int)fs.Length);
fs.Close();
string conn = "server=.;database=testDB;Uid=sa;Pwd=sa ";
SqlConnection myconn = new SqlConnection(conn);
myconn.Open();
string str = "insert into pro_table (pro_name,pro_file) values('测试文件',@file)";
SqlCommand mycomm = new SqlCommand(str, myconn);
mycomm.Parameters.Add("@file", SqlDbType.Binary, byData.Length);
mycomm.Parameters["@file"].Value = byData;
mycomm.ExecuteNonQuery();
myconn.Close();
} //从数据库中把二进制流读出写入还原成文件
private void button4_Click(object sender, EventArgs e)
{
string conn = "server=.;database=testDB;Uid=sa;Pwd=sa ";
string str = "select pro_file from pro_table where pro_name='测试文件' ";
SqlConnection myconn = new SqlConnection(conn);
SqlDataAdapter sda = new SqlDataAdapter(str, conn);
DataSet myds = new DataSet();
myconn.Open();
sda.Fill(myds);
myconn.Close();
Byte[] Files = (Byte[])myds.Tables[].Rows[]["pro_file"];
BinaryWriter bw = new BinaryWriter(File.Open("D:\\2.rdlc",FileMode.OpenOrCreate));
bw.Write(Files);
bw.Close(); }
最新文章
- 【转载】Java集合类Array、List、Map区别和联系
- elk平台搭建
- 通用权限管理系统多语言开发接口 - java,php 调用接口程序,多业务子系统集成
- HOJ 1640 Mobile Phone
- Repeater分页
- 阅读<;构建之法>;第三10、11、12章
- xss攻击和sq注入
- MacBook Pro 的照相机在哪?
- Sql 格式化工具
- Wikioi 1169 传纸条
- C#核编之字符串类型介绍与操作
- 我用的php开发环境是appserv一键安装,通过http://localhost测试成功,但是我有点不清楚的就是为什么访问.php文件要在地址栏上加上localhost(即http://localhost/text.php)才能成功访问?
- OSI模型第四层传输层--TCP协议
- Traffic Ccontrol(流量控制)
- labview生成可执行文件
- 微信网页授权获取用户openid及用户信息
- mongodb .explain(&#39;executionStats&#39;) 查询性能分析(转)
- python之路--BOM和DOM
- dockerfile 介绍
- php,mysql存储过程的简单例子
热门文章
- <;三>;年编程经验、何去何从?
- 【GISER &;&; Painter】矢量切片(Vector tile)番外一:Proj4js
- Spark源码分析:多种部署方式之间的区别与联系(转)
- iOS:切换视图的第三种方式:UITabBarController标签栏控制器
- c++学习之多态(虚函数和纯虚函数)
- Node.js:EventEmitter类
- Centos7 安装pycharm
- 解决Asp输出乱码问题
- [Grunt] External Config
- 推荐8款HTML5相关的特殊效果