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); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access