0

I am using TextFieldParser to parse the Subject and Issuer fields of an X509 certificate. For instance, if you look at the certificate on https://facebook.com, you would see

CN=*.facebook.com,O="Facebook, Inc.",L=Menlo Park,S=CA,C=US

Of course it'd be simple to split that line on commas, were it not for those pesky quotation marks. So I have to escape those. That's why I wanted to use TextFieldParser. My code:

string[] subjectPieces = null;

using (MemoryStream memStream = new MemoryStream(Encoding.ASCII.GetBytes(cert.Subject)))
using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(memStream))
{                
    parser.SetDelimiters(",");
    parser.HasFieldsEnclosedInQuotes = true;
    subjectPieces = parser.ReadFields();
}

When this code runs, subjectPieces will return:

CN=*.facebook.com
O="Facebook
Inc."
L=Menlo Park
S=CA
C=US

As you can see, it gave no regard to the field enclosed in quotation marks at all. I might as well have just used string.split(',').

I have tried setting HasFieldsEnclosedInQuotes to both true and false, with no effect. I have tried multiple character encodings for the stream, with no effect.

Ryan Ries
  • 2,381
  • 1
  • 24
  • 33

1 Answers1

2

I'm not an expert on CSV format, but I think the reason why this is happening is your example text is not a valid CSV format. As mentioned in here:

Fields with embedded commas or double-quote characters must be quoted.

In other words, for your example to be a proper CSV file, O="Facebook, Inc." would need to be "O=Facebook, Inc.", i.e. the entire field must be double-quoted.

So, to continue using the TextFieldParser class you would need to ensure the fields are quoted correctly and embedded double-quote characters are quoted.

Also, you may want to look at the following question for alternatives.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166