code_junkie

How do I extract the data in a FoxPro memo field using .NET?

Nov 13th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.46 KB | None | 0 0
  1. public static object GetDbaseOrFoxproRawValue(string DBPath, string TableName, string ColumnName,
  2. string CompareColumnName, string CompareValue, bool CompareColumnIsAutoKey)
  3. {
  4. using (BinaryReader read = new BinaryReader(File.Open(
  5. Path.Combine(DBPath, TableName + ".dbf"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
  6. {
  7. // Is it a type of file that I can handle?
  8. if (new byte[] { 0x02, 0x03, 0x30, 0x43, 0x63, 0x83, 0x8b,
  9. 0xcb, 0xf5, 0xfb }.Contains(read.ReadByte()))
  10. {
  11. // Skip date.
  12. read.BaseStream.Seek(3, SeekOrigin.Current);
  13.  
  14. // Read useful datas...
  15. uint RecordCount = read.ReadUInt32();
  16. ushort FirstRecord = read.ReadUInt16();
  17. ushort RecordLength = read.ReadUInt16();
  18. int FieldCount = FirstRecord - 296 / 32;
  19.  
  20. // Make sure things aren't stupid.
  21. ColumnName = ColumnName.ToLower();
  22. CompareColumnName = CompareColumnName.ToLower();
  23.  
  24. // Find target column (field)
  25. string temp;
  26. UInt32 CompareFieldOffset = uint.MaxValue, FieldOffset = uint.MaxValue;
  27. byte CompareFieldLength = 0, FieldLength = 0;
  28. char FieldType = ' ';
  29. for (int i = 0; i < FieldCount; i++)
  30. {
  31. read.BaseStream.Seek(32 + (i * 32), SeekOrigin.Begin);
  32. temp = Encoding.ASCII.GetString(read.ReadBytes(11)).Replace("", "").ToLower();
  33. if (temp == CompareColumnName)
  34. {
  35. read.ReadChar();
  36. CompareFieldOffset = read.ReadUInt32();
  37. CompareFieldLength = read.ReadByte();
  38. }
  39. if (temp == ColumnName)
  40. {
  41. FieldType = read.ReadChar();
  42. FieldOffset = read.ReadUInt32();
  43. FieldLength = read.ReadByte();
  44. }
  45.  
  46. if (CompareFieldOffset != uint.MaxValue && FieldOffset != uint.MaxValue)
  47. break;
  48. }
  49.  
  50. // Make sure we can continue.
  51. if (CompareFieldOffset == uint.MaxValue ||
  52. FieldOffset == uint.MaxValue) return null;
  53.  
  54. // Iterate through each record to find the one we want.
  55. for (int index = 0; index < RecordCount; index++)
  56. {
  57. read.BaseStream.Seek(FirstRecord + (index * RecordLength) + CompareFieldOffset, SeekOrigin.Begin);
  58. temp = Encoding.Default.GetString(read.ReadBytes(CompareFieldLength)).Replace("", "");
  59. if (temp == CompareValue)
  60. {
  61. read.BaseStream.Seek(FirstRecord + (index * RecordLength) + FieldOffset, SeekOrigin.Begin);
  62. switch (FieldType)
  63. {
  64. case 'M':
  65. case 'I': return read.ReadUInt32();
  66. case 'C':
  67. default: return Encoding.Default.GetString(read.ReadBytes(FieldLength)).Replace("", "");
  68. }
  69. }
  70. }
  71. }
  72. else
  73. {
  74. return null;
  75. }
  76. }
  77.  
  78. return null;
  79. }
Add Comment
Please, Sign In to add comment