|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
Download textfiledataset_src.zip - 6 KB IntroductionThis code allows you to generate and fill a
BackgroundEvery now and then I need to read some text file for importing data. Most of the times what I really need is a dataset with that data. But how to convert that text file to a dataset quickly? There are several articles here on codeproject that describe how to convert a csv file or a text file to a database or dataset (e.g. FinalCSVReader, DataSetFrmDelimTxt). But none of them were flexible enough, or offered data-validation. Using the codeGetting startedTo get started right away let us assume that we have a delimited file birthday.txt with the following content from which we want to create a 1,Chris,12-07-1972 2,Dave,03-01-1974 3,John,03-19-1980,Drummer 4,Mark,12-02-1980 5,Eric,09-18-1981 A quick way to get the // open the file
FileStream fileStream = new FileStream("birthday.txt", FileMode.Open, FileAccess.Read);
// create an instance of MyTextFileDataSet
TextFileDataSet MyTextFileDataSet = new TextFileDataSet();
// specify the regular expression for validating and recognising columns
MyTextFileDataSet.ContentExpression = new Regex("^(?<ID>[^,]+),(?<Name>[^,]+),(?<Date>[^,]+)$");
// fill the dataset
MyTextFileDataSet.Fill(fileStream);
// close the file
fileStream .Close();
The resulting Wondering where the column names came from, just take a look at the used regular expression: ^(?<ID>[^,]+),(?<Name>[^,]+),(?<Date>[^,]+)$
You can see that the names for the Without regular expressionsIf you are not familiar with regular expressions another approach is implemented to define the columns. RegexColumnBuilder MyColumBuilder = new RegexColumnBuilder();
MyColumBuilder.AddColumn("ID", ',');
MyColumBuilder.AddColumn("DATE", ',');
MyColumBuilder.AddColumn("NAME", ',');
Regex MyRegex = MyColumBuilder.CreateRegularExpression();
The MyTextFileDataSet.ColumnBuilder = MyColumnBuilder; Specify column typeIn the previous sample a column is defined with only a suitable delimiter. At this time there are four defined types available: INT, DOUBLE, DATE and STRING. The way to use these is: MyColumBuilder.AddColumn("ID", ',', RegexColumnType.INTEGER); MyColumBuilder.AddColumn("DATE", ',', RegexColumnType.DATE); To have the specified types present in the resulting dataset one must place the Large files
Points of InterestThe If you are not familiar with regular expressions, check out these articles and get started:
|
||||||||||||||||||||||