您的位置:首页 > 数据库

c# 动态实现xls,dwg等文件存取sqlserver数据库

2012-10-16 10:38 169 查看
有时,为了实现网络共享,我们可以采取数据库动态存取数据流的方式(数据库中的字段类型为image或者varbinary(Max)),管理文件,如下(一个winform中的测试代码):

string path = @"C:\Users\SN\Desktop\数控板检验图.dwg";//测试的dwg文件名

            string path1 = @"C:\Users\SN\Desktop\1.dwg";//保存读取后的文件的存放路径

            FileInfo fi = new FileInfo(path);

            FileStream fs = fi.OpenRead();

            //FileStream fs = fi.Open(FileMode);

            byte[] bytes = new byte[fs.Length];

            fs.Read(bytes, 0, bytes.Length);

            //Byte[] bytes = System.IO.File.ReadAllBytes(path3);

            //Assembly assem = Assembly.Load(bytes);

            string sqlsource = @"Data Source=.;Initial Catalog=****;Persist Security Info=True;User ID=****;Password=*****";//使用自己的数据库吧

            SqlConnection conn = new SqlConnection(sqlsource);

            conn.Open();

            SqlCommand comm = new SqlCommand("insert into aaa (g) values(@bbb)", conn);//数据表aaa有两个字段,自动递增的id和image格式的g

            comm.Parameters.Add("@bbb", System.Data.SqlDbType.Image);//这一句是必须要有的,通过此句,让数据库知道存进去的就是二进制信息

            comm.Parameters["@bbb"].Value = bytes;

            comm.ExecuteNonQuery();

            conn.Close();

           

            conn.Open();

            SqlCommand comm1 = new SqlCommand("select g from aaa where id in (select max(id) from aaa)", conn);

            Byte[] bts = (Byte[])comm1.ExecuteScalar();//读取数据表

            conn.Close();

            FileStream fs0 = new FileStream(path1, FileMode.CreateNew);//当自己没有创建路径为path1的文件时

            BinaryWriter bw = new BinaryWriter(fs0);

            bw.Write(bts, 0, bts.Length);

            bw.Flush();

            bw.Close();

            fs0.Close();

            //FileStream fs0;//也可以这样,这是路径下文件已经存在的情况下使用

            //FileInfo fi0 = new System.IO.FileInfo(path1);

            //fs0 = fi0.OpenWrite();

            //fs0.Write(bts, 0, bts.Length);

            //fs0.Close();

            //fs0 = fi0.OpenWrite();

            //fs0.Write(bytes, 0, bytes.Length);

            //fs0.Close();

            MessageBox.Show("ok");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息