I'd start with some best practices for parsing CSV files with the post Parsing CSV files in C#, with header.
I've also noticed you've got that "found" variable. Are you trying to avoid duplicate lines in your output file but the code is incomplete? I've written the following code under that assumption.
Here are the using statements:
using Microsoft.VisualBasic.FileIO; using System.Collections.Generic; using System.IO; using System.Linq;
Here's the main code:
List<string> foundLines = new List<string>(); using (TextFieldParser parser = new TextFieldParser(inputFilename)) { // Set up the parser for CSV files parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); using (StreamWriter writer = new StreamWriter(outputFilename, false)) { while (!parser.EndOfData) { string[] values = parser.ReadFields(); string serialNumber = values[0]; if (string.Equals(serialNumber, "XA2345")) { string line = string.Join(",", values.Select(Escape)); if (foundLines.Contains(line)) continue; // Skip writing this line more than once else foundLines.Add(line); // Remember this line for later writer.WriteLine(line); // Do what you need to with the individual column values string secondValue = values[1]; string thirdValue = values[2]; // ... Etc. ... } } } }
And here's a CSV helping method for escaping values as needed at Good CSV writer for C#:
static private string Escape(string s) { const string QUOTE = "\""; const string ESCAPED_QUOTE = "\"\""; char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' }; if (s.Contains(QUOTE)) s = s.Replace(QUOTE, ESCAPED_QUOTE); if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1) s = QUOTE + s + QUOTE; return s; }