欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现文件与二进制互转并存入数据库

程序员文章站 2023-11-05 22:48:28
//这个方法是浏览文件对象 private void button1_click(object sender, eventargs e) {...
//这个方法是浏览文件对象
    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[0].rows[0]["pro_file"]; 
      binarywriter bw = new binarywriter(file.open("d:\\2.rdlc",filemode.openorcreate));
      bw.write(files);
      bw.close();
       
    }