C#向数据库写二进制以及读出

1.C#把文件当作二进制流写进数据库

           

            SqlConnection myconnection = new SqlConnection(strsql);
            myconnection.Open();
            SqlCommand mycommand = new SqlCommand();

            FileInfo myfile = new FileInfo("D://**.*");
            FileStream mystream = myfile.OpenRead();
            byte[] mybyte = new byte[myfile.Length];
            mystream.Read(mybyte, 0, Convert.ToInt32(mystream.Length));

            strselect = "insert into DF_XML(DT,XML) values(getdate(),@file)";
            mycommand = new SqlCommand(strselect, myconnection);
            SqlParameter myparam0 = new SqlParameter("@file", SqlDbType.Binary);
            myparam0.Value = mybyte;
            mycommand.Parameters.Add(myparam0);
            mycommand.ExecuteNonQuery();
            mystream.Close();
            myconnection.Dispose();
            myconnection.Close();

3.C#把二进制流从进数据库读出并写入文件

            string strsql = "data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=MYDataBase";
            byte[] mybyte = null;
            FileStream myfs = new FileStream("D://data.xml", FileMode.CreateNew);
            BinaryWriter writefile = new BinaryWriter(myfs);
            string strselect = "select XML from DF_XML where ID=4";
            SqlConnection myconnection = new SqlConnection(strsql);
            myconnection.Open();
            SqlCommand mycommand = new SqlCommand(strselect, myconnection);
            SqlDataReader myreader = mycommand.ExecuteReader();
            if (myreader.Read())
            {
                mybyte = (byte[])myreader[0];
            }
            myreader.Close();
            myconnection.Close();
            writefile.Write(mybyte, 0, mybyte.Length);
            writefile.Close();
            myfs.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值