您可以先从数据库中获取架构(未经测试):
DataTable schema;
using (var con = new System.Data.SqlClient.SqlConnection(conStr))
{
var getSchemaSql = String.Format("SELECT * FROM {0}", tableName);
using (var schemaCommand = new System.Data.SqlClient.SqlCommand(getSchemaSql, con))
{
con.Open();
using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
schema = reader.GetSchemaTable();
}
}
}
然后是类似的东西:
for (int j = 0; j < schema.Rows.Count; j++)
{
DataRow schemaRow = schema.Rows[j];
Type dataType = schemaRow.Field<Type>("DataType");
int columnSize = schemaRow.Field<int>("ColumnSize");
if (dataType.FullName == "System.String")
{
String value = dr50[j] as String;
if (value != null)
value = value.Substring(0, columnSize);
}
}
同样,完全未经测试并从头开始编写,但它可能会让您了解如何获取列大小。当然,这仅适用于string
,但我认为这就是您想要的。