5.6. Modifying Data in a Text File
Problem
You need to modify the contents of a text file.
Solution
Use an OLE DB DataAdapter
together with parameterized SQL insert and update statements.
The solution uses the text file Category.txt shown in Figure 5-10.
Figure 5-10. Text file Category.txt
The solution creates a DataAdapter
and creates parameterized insert and update SQL statements. A DataSet
is created and filled from the text file using the DataAdapter
. The initial contents are output to the console. Next, a new row is added and the Update()
method of the DataAdapter
is called to update the text file. The DataSet
is reloaded and its contents output to the console. Finally, a row is updated and the Update()
method of the DataAdapter
is called to update the text file. The DataSet
is reloaded and its contents output to the console.
The C# code in Program.cs in the project ModifyTextFileData
is shown in Example 5-12.
Example 5-12. File: Program.cs for ModifyTextFileData solution
using System; using System.Data; using System.Data.OleDb; namespace ModifyTextFileData { class Program { static void Main(string[] args) { string oledbConnectString = "Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=..\..\..\;" + "Extended Properties=\"text;HDR=yes;FMT=Delimited\";"; string sqlSelect = "SELECT * FROM [Category.txt]"; // Create the connection OleDbConnection connection = new OleDbConnection(oledbConnectString); ...
Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.