使用OLE-DB从数据库中读取附加文件

时间:2012-08-05 19:07:33

标签: c# database ms-access oledb

我正在尝试使用C#读取Microsoft Access数据库。我正在使用OLE-DB类。问题是这段代码

OleDbDataReader reader = Command.ExecuteReader(); 
while (reader.Read())
{
    Console.WriteLine(reader.GetFieldType(0) + "\t" + reader.GetFieldType(1) + "\t" + reader.GetFieldType(2) +
            "\t" + reader.GetFieldType(3) + "\t" + reader.GetFieldType(4) + "\t" + reader.GetFieldType(5));
}

告诉我,第5个字段来自数据类型字符串。但它是一个附件。当我试图读取这个字符串时,它是空的。

System.Int32    System.String   System.String   System.Int32    System.DateTime    System.String

有没有办法从数据库中读取附件?

2 个答案:

答案 0 :(得分:4)

我意识到你要求OleDb,但是对于DAO,你可以这样说:

    DBEngine dbe = new DBEngine();
    Database db = dbe.OpenDatabase(@"z:\docs\test.accdb", false, false, "");
    Recordset rs = db.OpenRecordset("SELECT TheAttachment FROM TheTable", 
        RecordsetTypeEnum.dbOpenDynaset, 0, LockTypeEnum.dbOptimistic);

    Recordset2 rs2 = (Recordset2)rs.Fields["TheAttachment"].Value;

    Field2 f2 = (Field2)rs2.Fields["FileData"];
    f2.SaveToFile(@"z:\docs\ForExample.xls");
    rs2.Close();
    rs.Close();

参考:Programmatically managing Microsoft Access Attachment-typed field with .NET

答案 1 :(得分:0)

这有点棘手,但你不能只查询附件列,你只能得到文件名。您必须从附件列中的附件对象中选择值,然后拉出字节数组(存储在filedata中),然后通过Access删除添加到文件中的标题:

var connection = new OleDbConnection(connectionString);
connection.Open();
var dt = new DataTable("Attachments");
var dataAdapter = new OleDbDataAdapter(@"select attachmentColumn.FileData as filedata, attachmentColumn.FileName as filename, attachmentColumn.FileType as filetype from tablename", connection);
dataAdapter.Fill(dt);

foreach (DataRow row in dt.Rows)
{
  var filename = row["filename"].ToString();
  if (string.IsNullOrWhiteSpace(filename)) continue;
  var filedata = (byte[]) row["filedata"];
  int header = (int) filedata[0];
  byte[] actualFile = new byte[filedata.Length - header];
  Buffer.BlockCopy(filedata, header, actualFile, 0, actualFile.Length);
  // do stuff with byte array!
  File.WriteAllBytes("C:\\" + filename, actualFile);
}

请记住,Access会压缩未压缩的文件。更多关于here的信息。 希望这对你有用!