[ Team LiB ]Recipe 1.19 Connecting to a Text File
Problem
You want to use ADO.NET to access data stored in a text file.
Solution
Use the OLE DB Jet provider to access data in a text file.
The sample code creates an OleDbDataAdapter that uses the Jet OLE DB provider to
load the contents of the text file Categories.txt, shown in Example 1-13
, into a DataTable
and displays the contents in a data grid on the form.
Example 1-13. File: Categories.txt
"CategoryID","CategoryName","Description"
1,"Beverages","Soft drinks, coffees, teas, beers, and ales"
2,"Condiments","Sweet and savory sauces, relishes, spreads, and seasonings"
3,"Confections","Desserts, candies, and sweet breads"
4,"Dairy Products","Cheeses"
5,"Grains/Cereals","Breads, crackers, pasta, and cereal"
6,"Meat/Poultry","Prepared meats"
7,"Produce","Dried fruit and bean curd"
8,"Seafood","Seaweed and fish"
The C# code is shown in Example 1-14
.
Example 1-14. File: ConnectTextFileForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Windows.Forms;
using System.Data;
[Categories.txt]
Format=CSVDelimited
ColNameHeader=True
MaxScanRows=0
Character=OEM
Col1=CategoryID Long Width 4
Col2=CategoryName Text Width 15
Col3=Description Text Width 100
The schema.ini file provides the following schema information about the data in the text
file:
•
Filename
•
File format
•
Field names, widths, and data types
•
Character set
•
Special data type conversions
The first entry in the schema.ini file is the text filename enclosed in square brackets. For
example:
[Categories.txt]
The Format option specifies the text file format. Table 1-8
describes the different options.
Table 1-8. Schema.ini format options
Format Description
CSV
Delimited
Fields are delimited with commas:
The parameters in the entry are:
columnName
The name of the column. If the column name contains spaces, it must be enclosed
in double quotation marks.
dataType
The data type of the column. This value can be Bit, Byte, Currency, DateTime,
Double, Long, Memo, Short, Single, or Text.
DateTime values must be in one of the following formats: dd-mmm-yy, mm-dd-
yy, mmm-dd-yy, yyyy-mm-dd, or yyyy-mmm-dd, where mm is the month number
and mmm are the characters specifying the month.
Width n
The literal value Width followed by the integer value specifying the column width.
The Character option specifies the character set; you can set it to either ANSI or OEM.
[ Team LiB ]