I need help to split a record in a CSV file using C # Split command

The record I'm trying to split is formatted as follows:

987,"This is second field, it contains multiple commas, but is enclosed in quotes, 88123, 99123", 1221, lastfield 

I am using the code:

 char[] delimiters = new char[] {',' }; string[] parts = line.Split(delimiters, StringSplitOptions.None); 

I get split results, but do not process the delimited field with a quote as one field. I need to get a result of 4 fields, but I get a field for each comma. How to configure / change the code to get the desired results?

+4
source share
2 answers

string.Split() not enough for this. You will need to use regular expressions (in C #, the Regex class).

0
source

@Tavya is true that String.Split will not work for you, since it does not process quoted strings. There are many ways to trick this notorious cat, including regular expressions or using one of the many CSV parsers found on a Google search.

Another simple approach would be to use the VisualBasic TextFieldParser class. Just place the link in your project on Microsoft.VisualBasic.dll and "using Microsoft.VisualBasic.FileIO" in the file header. Then you can do something like this.

  private List<string> parseFields (string lineToParse) { //initialize a return variable List<string> result = new List<string>(); //read the line into a MemoryStream byte[] bytes = Encoding.ASCII.GetBytes(lineToParse); MemoryStream stream = new MemoryStream(bytes); //use the VB TextFieldParser to do the work for you using (TextFieldParser parser = new TextFieldParser(stream)) { parser.TextFieldType = FieldType.Delimited; parser.Delimiters = new string[] { "," }; parser.HasFieldsEnclosedInQuotes = true; //parse the fields while ( parser.EndOfData == false) { result = parser.ReadFields().ToList(); } } return result; } 

Results will be:

987

This is the second field, it contains several commas, but is enclosed in quotation marks, 88123,
99123

1 221

lastfield

0
source

Source: https://habr.com/ru/post/1492155/


All Articles