简单的winform 利用OpenFileDialog浏览文件读取zip格式文件并转换为二进制数据保存至数据库...

本文介绍了一种使用C#中的SqlCommand组件及其参数化功能来更新数据库的方法。具体地,通过读取一个.zip文件并将其转换为byte数组,然后将这个数组作为参数传递给SqlCommand,最终实现对数据库中image字段的有效更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

            Stream ms;
            byte[] dllbyte;
            OpenFileDialog ofdSelectPic = new OpenFileDialog();
            ofdSelectPic.DefaultExt = "压缩文件.zip|*.zip";
            ofdSelectPic.Filter = "压缩文件.zip|*.zip";
            if (ofdSelectPic.ShowDialog() == DialogResult.OK)
            {
                if ((ms = ofdSelectPic.OpenFile()) != null)
                {
                    string filepath = ofdSelectPic.FileName;

                    string extension = Path.GetExtension(filepath);
                    if (extension == ".zip")
                    {
                        dllbyte = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(dllbyte, 0, Convert.ToInt32(ms.Length));
                        int count = updateSql(textBox1.Text, Convert.ToInt32(ms.Length),dllbyte);
                            if (count > 0)
                            {
                                
                                this.Close();
                                MessageBox.Show("上传成功!");
                              
                               
                            }
                            else
                                MessageBox.Show("上传失败!");
                            ms.Close();
                    }

                }

            }

 

 public  int updateSql(string Version,int filesize,byte[] dll)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            string sqlstr = string.Format("update sys_verfile set version = '{0}',filesize='{1}',filebody=@img ", Version, filesize);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sqlstr;
            cmd.Connection = conn;
            cmd.Parameters.Add("@img", System.Data.SqlDbType.Image);
            cmd.Parameters[0].Value = dll;
            conn.Open();
            int result = Convert.ToInt32(cmd.ExecuteNonQuery());
            return result;

        }

PS:在写更新语句时 发现image类型字段 直接赋值为获取到的byte[]后 无法更新压缩包里的数据,但是利用SqlCommand,  声明参数类型为System.Data.SqlDbType.Image时  update后就入库了 ,以后再做了解。

 

转载于:https://www.cnblogs.com/wyh329861784/p/5607434.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值