A DotNet Raider

My adventures in the .NET world!
posts - 49, comments - 12, trackbacks - 0

My Links

News

Website View Martino Bordin's profile on LinkedIn

Archives

Post Categories

giovedì 22 ottobre 2015

Parsing di file CSV

Molte volte capita di dover effettuare il parsing di file CSV.

L’implementazione può diventare complessa a piacere (basti pensare all’escape dei caratteri, personalizzazione dei delimitatori, etc) e per questo esistono già librerie che ci permettono di effettuare questa operazione facilmente.

Non tutti sanno (ecco il perchè di questo post) che il framework .NET fornisce già questa funzionalità .

La classe in questione è TextFieldParser, contenuto nell’assembly Microsoft.VisualBasic.

using (TextFieldParser parser = new TextFieldParser(@"C:\temp\sample.csv"))
            {
                parser.CommentTokens = new[] { "#" };
                parser.SetDelimiters(";");
                parser.HasFieldsEnclosedInQuotes = true;

                // Skip over header line.
                //parser.ReadLine();

                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    if (fields != null)
                    {
                        var specificCulture = System.Globalization.CultureInfo.CreateSpecificCulture("it-IT");
                        var foo = new 
                        {
                            Field1 = fields[0],
                            Field2 = int.Parse(fields[1], specificCulture),
                            Field3 = double.Parse(fields[1], specificCulture),
                            Field4 = DateTime.Parse(fields[1], specificCulture),
                        };
                    }
                }
            }

posted @ lunedì 1 gennaio 0001 00:00 | Feedback (1) |

Powered by:
Powered By Subtext Powered By ASP.NET