The code provided above will append records to the file indefinitely no matter the state of the data.
AppendAllText will keep appending the same data to the file. The type of file created in the code provided seems to indicate it is meant to be delimiter separated value file. These are generally meant to be one-way operations of Read/Write (note the exclusion of Update and Insert). A few suggestions:
1. The code provided is using data from the
DataTable to update the file. Therefore, make sure there is code to update the DataTable when a user makes a change, otherwise the new data will never make it to the file. The database, specifically, will need to be updated to include the user changes.
2. Consider recreating the file as apposed to appending. The code provided will keep appending all of the data in the DataTable upon each timer iteration generating duplicate data in the file. By creating/opening the file, overwriting the text inside it, and closing the file will prevent the duplicate data issue. To do this a combination of
File methods will be needed:
OpenWrite and
WriteAllText
3. Assuming scalability was in mind, parsing the file will be needed. The idea is to open the file, look for the particular record, update the record, and then save/close the file. To parse the file there must be a way to uniquely identify the record to update. At this point, a text file is beginning to be more unsuitable from a maintenance stand point. There are libraries available to manage CSV files such as
LINQ-to-CSV Library - Code Project and
FileHelpers.
4. Use an XML file instead. The .NET framework has great support for XML file management. More information about this can be found on MSDN. Please reference
XMLDocument,
DataSet and XmlDataDocument Synchronization, and
Create, Modify and Read XML Files in C#.