C# Access 二进制文件读写

我写的一个类,注意二进制文件操作的部分不通用,需要根据具体情况去改

using System;
using System.Data;
using System.Configuration;
using System.Data.OleDb;
using System.Collections;
using System.Windows.Forms;

namespace AccessOperator
{
    public class AccessHelper
    {
        #region 属性
        private OleDbConnection conn;
        // private OleDbCommand cmd;
        #endregion

        #region 打开Access
        /// 
        /// 打开连接
        /// 
        /// 完整路径,//
        /// 无用户名,则参数为""
        /// 无密码,则参数为""
        public AccessHelper(string AccessPath, string UserName, string UserPWD)
        {
            try
            {
                //组成数据库连接字符串
                string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + AccessPath + ";";
                if (UserName != string.Empty && UserPWD != string.Empty)
                {
                    ConnStr += "User Id=" + UserName + "; Password=" + UserPWD + ";";
                }
                conn = new OleDbConnection(ConnStr);
                conn.Open();
                if (conn.State != ConnectionState.Open)
                {
                    MessageBox.Show("数据库连接异常");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接异常,请确保Access文件存在,用户名、密码正确");
            }
        }
        #endregion

        /// 
        /// 返回受影响的行数
        /// 
        /// SQL 语句
        /// 返回受影响的函数
        public int ExecuteNonQuery(string cmdText)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, conn, cmdText);
            try
            {
                int count = cmd.ExecuteNonQuery();
                return count;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        // 返回一个DataReader对象
        public OleDbDataReader ExecuteReader(string cmdText)
        {
            //创建一个SqlCommand对象
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, conn, cmdText);
            try
            {
                OleDbDataReader reader = cmd.ExecuteReader();
                return reader;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        // 返回数据集
        public DataSet ExecuteDataSet(string cmdText)
        {
            //创建一个SqlCommand对象,并对其进行初始化
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, conn, cmdText);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                //填充ds
                da.Fill(ds);
                return ds;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }


        //返回结果集的第一列
        public object ExecuteScalar(string cmdText)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, conn, cmdText);
            object val = cmd.ExecuteScalar();
            return val;
        }

        // 执行SQL前的准备
        private void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, string cmdText)
        {
            //判断连接的状态。如果是关闭状态,则打开
            if (conn.State != ConnectionState.Open)
                conn.Open();
            //cmd属性赋值
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = CommandType.Text;
            //添加cmd需要的存储过程参数
        }

        #region - 二进制文件用,不操作文件系统时可以删除 -
        //二进制文件的保存
        //表的结构:三列,Title、Description、nr,类型分别为, 文本 文本 Ole对象
        public void SaveBinaryData(string strFileName, string strHD, string strZH, string strPic)
        {
            System.IO.FileStream fs = new System.IO.FileStream(strFileName, System.IO.FileMode.Open);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
            byte[] buffer = br.ReadBytes((int)fs.Length);
            OleDbCommand command = new OleDbCommand("INSERT INTO 图形绘制知识库(巷道类型,支护类型,图形类型,绘图知识)" +
            "VALUES (@HDStyle,@ZHMode,@PicType,@nr)", conn);

            command.Parameters.AddWithValue("@HDStyle", strHD);
            command.Parameters.AddWithValue("@ZHMode",  strZH);
            command.Parameters.AddWithValue("@PicType", strPic);
            command.Parameters.AddWithValue("@nr", buffer);

            command.ExecuteNonQuery();
            br.Close();
            fs.Close();
            MessageBox.Show("保存完毕。");
            OleDbCommand cmd = new OleDbCommand();
        }

        /// 
        /// 导出二进制数据
        /// 
        /// 文件名称,表中第一个字段
        /// 文件保存路径,全路径
        public void ExportBinaryData(string strSavePath, string strHD, string strZH, string strPic)
        {
            //构建数据库连接,SQL语句,创建参数
            OleDbCommand command = new OleDbCommand("select top 1 * from 图形绘制知识库 where 巷道类型 = \"" + strHD + "\" and 支护类型 = \"" + strZH + "\" and 图形类型 = \"" + strPic + "\"", conn);
            OleDbDataReader dr = command.ExecuteReader();
            byte[] buff = null;
            if (dr.Read())
            {
                buff = (byte[])dr["绘图知识"];
            }

            if (System.IO.File.Exists(strSavePath))
                System.IO.File.Delete(strSavePath);

            System.IO.FileStream stream = new System.IO.FileStream(strSavePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(stream);
            bw.Write(buff);
            bw.Close();
            stream.Close();
            MessageBox.Show("生成完毕。");
        }
        #endregion

        // 关闭连接、释放资源
        public void CloseConn()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
}


 

下面是网友的一个例子,主要功能是把Word文档存入Access,需要的时候再导出来

网址:http://social.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/d4a419b1-c51b-4e87-a151-9ca858897570

完整代码:在Office 2007,W2k3 SP2,VS2008 SP1下测试通过

using System;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private string strCnn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\c\WindowsFormsApplication7\aspxWeb.mdb;Persist Security Info=True";
    private void button2_Click(object sender, EventArgs e)
    {
      if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
      {
        this.textBox1.Text = this.openFileDialog1.FileName;
      }
    }

    private void button1_Click(object sender, EventArgs e)
    {
      if (this.textBox1.Text.Equals(String.Empty))
      {
        MessageBox.Show("先选择文件。");
        return;
      }

      FileStream fs = new FileStream(this.textBox1.Text, FileMode.Open);
      BinaryReader br = new BinaryReader(fs);
      byte[] buffer = br.ReadBytes((int)fs.Length);
      OleDbConnection myConnection = new OleDbConnection(strCnn);
      OleDbCommand command = new OleDbCommand("INSERT INTO TestTable (Title,Description,nr)" +
      "VALUES (@Title,@Description,@nr)", myConnection);

      command.Parameters.AddWithValue("@Title", "a");
      command.Parameters.AddWithValue("@Description", "[email protected]");
      command.Parameters.AddWithValue("@nr", buffer);

      //打开连接,执行查询
      myConnection.Open();
      command.ExecuteNonQuery();
      myConnection.Close();
      br.Close();
      fs.Close();
      MessageBox.Show("保存完毕。");
    }

    private void button3_Click(object sender, EventArgs e)
    {
      //构建数据库连接,SQL语句,创建参数
      OleDbConnection myConnection = new OleDbConnection(strCnn);
      myConnection.Open();
      OleDbCommand command = new OleDbCommand("select top 1 * from TestTable Order By id DESC", myConnection);
      OleDbDataReader dr = command.ExecuteReader();
      byte[] buff = null;
      if (dr.Read())
      {
        buff = (byte[])dr["nr"];
      }

      String p = Application.ExecutablePath;
      p = p.Substring(0,p.LastIndexOf("\\"));
      p +=  "\\m.doc";
      this.textBox2.Text = p ;
      if (File.Exists(p)) File.Delete(p);
      myConnection.Close();
      System.IO.FileStream stream = new System.IO.FileStream(p, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
      System.IO.BinaryWriter bw = new System.IO.BinaryWriter(stream);
      bw.Write(buff);
      bw.Close();
      stream.Close();
      MessageBox.Show("生成完毕。");
    }
  }
}


 

 

你可能感兴趣的:(C#学习笔记)