C#从Access .accdb读取附件

时间:2015-02-28 20:22:43

标签: c# ms-access odbc

我必须从.accdb文件中读取一个表并将其迁移到数据库。 我无法在将要执行迁移的服务器上安装MS Access! 目前我使用ODBC

OdbcConnection DbConnection = new OdbcConnection("DSN=SAMPLE_ISAM");
DbConnection.Open();
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = "SELECT Attachments FROM SomeTable";
OdbcDataReader DbReader = DbCommand.ExecuteReader();
while (DbReader.Read())
{
    object att = DbReader["Attachments"];
}
DbReader.Close();
DbCommand.Dispose();
DbConnection.Close();

SAMPLE_ISAM指向accdb文件。 这适用于简单的数据类型,但对于附件,它只获取文件名(我也需要字节)。

正如我所说无法安装MS Access所以Interop DAO不是一个选项。

有没有办法获得附件?其他技术和编程语言也是可以接受的。

2 个答案:

答案 0 :(得分:3)

感谢Steve,我发现了Extracting files from an Attachment field in an Access database

所以工作代码是:

            OdbcConnection DbConnection = new OdbcConnection("DSN=SAMPLE_ISAM");
            DbConnection.Open();
            OdbcCommand DbCommand = DbConnection.CreateCommand();
            DbCommand.CommandText = "SELECT Attachments.FileData, ID, Attachments.FileName FROM Complaints WHERE ID IN(29,30)";
            OdbcDataReader DbReader = DbCommand.ExecuteReader();
            int fCount = DbReader.FieldCount;
            while (DbReader.Read())
            {
                byte[] bytes = (byte[])DbReader[0];
                Int32 ID = (Int32)DbReader[1];
                string name = (string)DbReader[2];
                File.WriteAllBytes(@"D:\files\" + name, bytes.Skip(20).ToArray());
            }
            DbReader.Close();
            DbCommand.Dispose();
            DbConnection.Close();
using System.Linq;需要

Skip(20)(请参阅链接)。 对于pdf和jpg,元数据是20个字节。请注意,它可能因其他文件类型而异。

答案 1 :(得分:0)

我不确定标题格式是什么,但第一个字节会告诉你标题的长度,以扩展evgeni的例子:

        OdbcConnection DbConnection = new OdbcConnection("DSN=SAMPLE_ISAM");
        DbConnection.Open();
        OdbcCommand DbCommand = DbConnection.CreateCommand();
        DbCommand.CommandText = "SELECT Attachments.FileData, ID, Attachments.FileName FROM Complaints WHERE ID IN(29,30)";
        OdbcDataReader DbReader = DbCommand.ExecuteReader();
        int fCount = DbReader.FieldCount;
        while (DbReader.Read())
        {
            byte[] bytes = (byte[])DbReader[0];
            Int32 ID = (Int32)DbReader[1];
            string name = (string)DbReader[2];
            File.WriteAllBytes(@"D:\files\" + name, bytes.Skip((int)bytes[0]).ToArray());
        }
        DbReader.Close();
        DbCommand.Dispose();
        DbConnection.Close();

但是如果附件中有多个文件,我认为这不会起作用...怀疑标题还会告诉偏移量为5的附件数量,但是需要更多的测试才能看出这是否是案件。

相关问题