Chirag Atha
Chirag Atha

Reputation: 11

Delete rows with null values from a csv file in c#

How can I delete a row which contains null values from a comma separated csv file in c# ?

Example:
|      FirstName      |     LastName     |      Email    |    Address   |
|---------------------|------------------|---------------|--------------|
|          lmn        |         lmn      |[email protected]    |DemoAddress   |
|          xy         |         xy       |[email protected]      |DemoAddress   |
|          demo       |         demo     |               |              |
|          demo2      |         demo2    |[email protected]      |DemoAddress   |

    

Outcome:
|      FirstName      |     LastName     |      Email    |    Address   |
|---------------------|------------------|---------------|--------------|
|          lmn        |         lmn      |[email protected]    |DemoAddress   |
|          xy         |         xy       |[email protected]      |DemoAddress   |
|          demo2      |         demo2    |[email protected]      |DemoAddress   |

I tried the following code but doesn't work as expected

        private string filterCSV(string strFilePath) 
        { 
            var columnIndex = 3;
            var line = File.ReadAllLines(strFilePath);
            var n = line.Where(x => x[columnIndex].Equals(""));
            string result = string.Join("\r", not.ToArray());

            return result;

        }

Upvotes: 0

Views: 457

Answers (1)

Chirag Atha
Chirag Atha

Reputation: 11

Adding answer for future reference

private void RemoveBlanks(string datapath)
        {
            List<CSV> records;
            using (var reader = new StreamReader(datapath))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                records = csv.GetRecords<CSV>().ToList();
                for(int i = 0; i < records.Count;++i)
                {
                    if (records[i].Email== "" && records[i].Address == "")
                    {
                        
                        records.RemoveAt(i);
                    }
                }

            }
            using (var writer = new StreamWriter(datapath))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                csv.WriteRecords(records);
            }           
        }

Upvotes: 1

Related Questions