我一直在编写一个程序来读取 dbf 文件,处理数据并将其保存回 dbf。我遇到的问题与写作部分有关。
private const string constring = "Driver={Microsoft dBASE Driver (*.dbf)};"
+ "SourceType=DBF;"
+ "DriverID=277;"
+ "Data Source=¿;"
+ "Extended Properties=dBASE IV;";
private const string qrystring = "SELECT * FROM [¿]";
public static DataTable loadDBF(string location)
{
string filename = ConvertLongPathToShort(Path.GetFileName(location));
DataTable table = new DataTable();
using(OdbcConnection conn = new OdbcConnection(RTN(constring, filename)))
{
conn.Open();
table.Load(new OdbcCommand(RTN(qrystring, filename), conn).ExecuteReader());
conn.Close();
}
return table;
}
private static string RTN(string stmt, string tablename)
{ return stmt.Replace("¿", tablename); }
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(
String path, // input string
StringBuilder shortPath, // output string
Int32 shortPathLength); // StringBuilder.Capacity
public static string ConvertLongPathToShort(string longPathName)
{
StringBuilder shortNameBuffer;
int size;
shortNameBuffer = new StringBuilder();
size = GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity);
if (size >= shortNameBuffer.Capacity)
{
shortNameBuffer.Capacity = size + 1;
GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity);
}
return shortNameBuffer.ToString();
}
这就是我正在使用的。我已经尝试了多种方法来编写一个新文件,但都没有成效。老实说,虽然通常我会提倡形式和功能,但我只是想让该死的东西工作,这个应用程序应该做一件非常具体的事情,它不会模拟天气。
-=# 编辑 #=-
由于时间压力,我已经停止使用该应用程序,但在我放弃它之前,我意识到我正在使用的特定格式的 dbf 没有主键信息。这当然意味着我必须从本质上将数据读取到 DataTable,弄乱它,然后擦除 dbf 中的所有记录并从头开始插入所有内容。把它搞砸了。