SQLTeam.com | Weblogs | Forums

Csv to c# object


#1

how to read the data from csv file to object variable..writing in C# script component..

T.I.A


#2

there are plenty of links online to do this, but I would ask why? If you are using SSIS, why not use DataFlow?


#3

What are you trying to accomplish? There are probably better options available - but if you need to be able to parse a CSV string from C# then one option would be to include the Visual Basic FileIO namespace:

using Microsof.VisualBasic.FileIO;

Then - you can utilize TextFieldParser to parse the CSV string:

        TextReader strReader = new StringReader(Row.RecordData);
        using (TextFieldParser csvParser = new TextFieldParser(strReader)
        {
            Delimiters = new string[] { "," },
            TextFieldType = FieldType.Delimited,
            HasFieldsEnclosedInQuotes = true
        })
        {
            while (csvParser.EndOfData == false)
            {

I have utilized the above when parsing a text file where there are sections of that file that are CSV formatted rows. The code has to loop through each row in the file and determine if we need to process that rows data - and if so we fall into the loop that processes the record as CSV data.

If you just have a simple CSV file then doing the above is a lot of extra work that isn't needed.