从access中提取文件

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

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

namespace Files2Access
{
      public class access2file
      {
            private string fileName;
            private string accessName;

            public access2file(string s1,string s2)
            {
                  fileName = s1;
                  accessName = s2;
            }

            public access2file()
            {
                  fileName = @"c:\noname";
                  this.accessName = @"E:\mine\tiku.mdb";
            }
           
            public bool extractFile(string uNeedFileName)
            {
                  try
                  {
                        byte[] bData = null;

                        OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + accessName);

                        string strQuery = "SELECT Content FROM StorageQ "
                                                            + " WHERE FileName = " +"'"+ uNeedFileName+"'";


                        conn.Open();

                        OleDbCommand comm = new OleDbCommand(strQuery, conn);


                        OleDbDataReader dr = comm.ExecuteReader();

                        while (dr.Read())
                        {
                              bData = (byte[])dr["Content"];
                        }
                        conn.Close();
                        dr.Close();

                        if (bData != null)
                        {

                              // Save file

                              FileInfo fi = new FileInfo(fileName);

                              if (!fi.Exists)
                              {

                                    //Create the file.

                                    using (FileStream fs = fi.Create())
                                    {

                                          fs.Write(bData, 0, bData.Length);

                                    }

                              }

                              else
                              {

                                    //Create the file.

                                    using (FileStream fs = fi.OpenWrite())
                                    {

                                          fs.Write(bData, 0, bData.Length);

                                    }

                              }

                        }
                        return true;
                  }
                  catch (Exception e)
                  {
                        return false;
                  }
                 
            }
      }
}

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