Delete or Modify a row in CSV file

ashok.k

Member
Joined
Jun 26, 2009
Messages
13
Programming Experience
Beginner
Hi

I would like to fetch a few rows in a CSV file and update its contents.

How to fetch a particular record in a CSV file? It has an unique id in every row.

Can I record in a CSV file be updated directly? Or Should all the contents of a CSV file be read into a CSV reader or

StreamReader object and modified and then re written as a new CSV file?

Thanks
Ashok
 
You can only really work with the file in-place if the columns are fixed-width, because any data you write will take up exactly the same amount of space as the old data. As fields are variable-width in a CSV file, you will have to read the whole file into your app, process them and then write them back out again. You can use a StreamReader to read the data but I would suggest using a TextFieldParser.

That will allow you to read the file line by line with each line read as a String array of fields. Whether you then process a record further, e.g. into instances of your own entity type, is up to you. Either way, you can add each record to a generic List and then you can use LINQ to Objects to query that List.

Once you're done, you can loop through the List and write each record out using a StreamWriter. You will need to package each record into a single String to be written, which may be as simple as calling String.Join or maybe more complex, depending on the data and the way you store it.
 
Back
Top