C# Jet byte[]
时间: 2023-07-19 12:47:58 浏览: 172
你可以使用以下代码将 Jet 数据库中的表转换为 byte[] 数组:
```csharp
public byte[] ConvertJetTableToByteArray(string connectionString, string tableName)
{
byte[] byteArray = null;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// 获取表的记录数
OleDbCommand command = new OleDbCommand($"SELECT COUNT(*) FROM [{tableName}]", connection);
int recordCount = (int)command.ExecuteScalar();
// 获取表的字段数和字段类型
command.CommandText = $"SELECT TOP 1 * FROM [{tableName}]";
DataTable schemaTable = new DataTable();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
dataAdapter.FillSchema(schemaTable, SchemaType.Source);
int fieldCount = schemaTable.Columns.Count;
List<Type> fieldTypes = new List<Type>();
for (int i = 0; i < fieldCount; i++)
{
fieldTypes.Add(schemaTable.Columns[i].DataType);
}
// 构造 byte[] 数组
byteArray = new byte[4 + fieldCount * 2 + recordCount * fieldCount * 2];
BinaryWriter binaryWriter = new BinaryWriter(new MemoryStream(byteArray));
binaryWriter.Write(recordCount);
binaryWriter.Write(fieldCount);
for (int i = 0; i < fieldCount; i++)
{
binaryWriter.Write((short)Type.GetTypeCode(fieldTypes[i]));
binaryWriter.Write((short)Encoding.Unicode.GetByteCount(schemaTable.Columns[i].ColumnName));
binaryWriter.Write(Encoding.Unicode.GetBytes(schemaTable.Columns[i].ColumnName));
}
command.CommandText = $"SELECT * FROM [{tableName}]";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < fieldCount; i++)
{
if (reader.IsDBNull(i))
{
binaryWriter.Write((short)0);
}
else
{
object fieldValue = reader.GetValue(i);
byte[] fieldBytes = null;
switch (Type.GetTypeCode(fieldTypes[i]))
{
case TypeCode.Boolean:
fieldBytes = BitConverter.GetBytes((bool)fieldValue);
break;
case TypeCode.Byte:
fieldBytes = new byte[] { (byte)fieldValue };
break;
case TypeCode.Char:
fieldBytes = Encoding.Unicode.GetBytes(new char[] { (char)fieldValue });
break;
case TypeCode.DateTime:
fieldBytes = BitConverter.GetBytes(((DateTime)fieldValue).ToOADate());
break;
case TypeCode.Decimal:
fieldBytes = ((decimal)fieldValue).ToByteArray();
break;
case TypeCode.Double:
fieldBytes = BitConverter.GetBytes((double)fieldValue);
break;
case TypeCode.Int16:
fieldBytes = BitConverter.GetBytes((short)fieldValue);
break;
case TypeCode.Int32:
fieldBytes = BitConverter.GetBytes((int)fieldValue);
break;
case TypeCode.Int64:
fieldBytes = BitConverter.GetBytes((long)fieldValue);
break;
case TypeCode.Single:
fieldBytes = BitConverter.GetBytes((float)fieldValue);
break;
case TypeCode.String:
fieldBytes = Encoding.Unicode.GetBytes((string)fieldValue);
break;
}
binaryWriter.Write((short)fieldBytes.Length);
binaryWriter.Write(fieldBytes);
}
}
}
binaryWriter.Close();
}
return byteArray;
}
```
在上面的代码中,我们首先打开 Jet 数据库连接,并获取目标表的记录数和字段信息。然后,我们使用 `BinaryWriter` 将表的记录和字段写入 `MemoryStream` 中,并将 `MemoryStream` 转换为 byte[] 数组并返回它。最后,我们关闭 `BinaryWriter` 和 `MemoryStream` 对象以释放资源。
阅读全文