Tech Tip: Open a CSV file using C# .NET

Tech Tip: Open a CSV file using C# .NET

There are many occasions where you need to read data from a CSV file.  We commonly work with CSV files while doing data migrations from one system to another or when integrating between two systems.  Doing this using C# is not very difficult.

The simplest way to do so is to add a reference in your project to the Microsoft.VisualBasic assembly.  (Don’t worry, you can still safely use this in C#.) Right click on the References option in your project Solution Explorer and choose Add Reference.

The following method will read your CSV file and return a standard DataTable object. You can easily work from this DataTable.  Please note that if you are going to use this in a production environment, you will probably want to add some exception handling and commenting.

        public static DataTable ReadCSVFile(String filename)

        {

            DataTable table = new DataTable();

 

            using (TextFieldParser csvParser = new TextFieldParser(filename))

            {

                csvParser.CommentTokens = new string[] { "#" };

                csvParser.SetDelimiters(new string[] { "|" });

                csvParser.HasFieldsEnclosedInQuotes = false;

 

 

                string[] fields = csvParser.ReadFields();

                foreach (String field in fields)

                {

                    table.Columns.Add(field);

                }

 

 

                while (!csvParser.EndOfData)

                {

                    String[] data = csvParser.ReadFields();

                    DataRow dr = table.NewRow();

                    for (int i = 0; i < table.Columns.Count; i++)

                    {

                        dr[i] = data[i];

                    }

                    table.Rows.Add(dr);

                }

            }

 

            return table;

        }

From here you simply loop through the DataTable rows.  Easy!

The best part of this is that it is very easy to modify this to work with tab delimited files or any other delimiter. 

TopLine Results specializes in CRM solutions and has extensive experience working will all manner of data.  Contact us for more information!

About the Author
Dan Boehm is our senior developer and lead engineer for CRM implementation projects. With more than ten years of Microsoft .NET and CRM experience, Dan specializes in complex CRM development and migration projects with an emphasis on creative solutions which meet and surpass client expectations.


Leave a comment!

You must be logged in to post a comment.