将文件保存到access中

Posted on 2007-10-07 15:47  winder  阅读(401)  评论(0)    收藏  举报

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.OleDb;

namespace Files2Access
{
      /// <summary>
      /// 任意文件保存到access数据库中
      /// 注意:数据库格式!!!
      /// </summary>
      public class File2Access
      {
           
            private string accessName;
            /// <summary>
            /// 指定access路径
            /// </summary>
            /// <param name="s">路径名</param>
            public File2Access(string s)
            {
                  this.accessName = s;
            }
            /// <summary>
            ///使用默认access路径
            /// </summary>
            public File2Access()
            {
                  this.accessName =@"E:\mine\tiku.mdb";
            }
            /// <summary>
            /// 将文件保存到access数据库中
            /// </summary>
            /// <param name="access">access数据库的路径</param>
            /// <param name="file">要保存的文件</param>
            /// <returns></returns>
            public bool insert2access(FileInfo file)
            {
                  OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+accessName);
                  if (file.Exists)
                  {
                        byte[] bdata = null;

                        using (FileStream fs = file.OpenRead())
                        {
                              bdata = new byte[file.Length];
                              int nReadLength = fs.Read(bdata, 0, (int)file.Length);
                        }
                        string strQuery = "INSERT INTO StorageQ "

                                                               + " ( FileName, Content) "

                                                               + " VALUES "

                                                               + " ( @FileName, @Content ) ";

                        OleDbCommand comm = new OleDbCommand(strQuery, conn);

                        comm.Parameters.Add("@FileName", file.Name);

                        comm.Parameters.Add("@Content", bdata);

                        conn.Open();
                        comm.ExecuteNonQuery();
                        return true;
                  }
                  else
                  {
                        return false;
                  }


            }
      }
}

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3