Reading and Writing Delimited Files in .Net Core

Reading and Writing Delimited Files in .Net Core

I often need to read and write files in delimited files from within a .Net Core application. It seems that there is no inbuilt parser for doing this so I wrote one.

The code consists of a single static class “DelimtedFile” that has two methods, one to read a delimited file and one to write one.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ReadAndWriteDelimtedFiles
{
    public static class DelimtedFile
    {
        /// <summary>
        /// Reads a delimited file into a List of strings lists.
        /// </summary>
        /// <param name="filePath">The path to the file</param>
        /// <param name="delimter">The delimiter used 
        /// to parse the items within each line of the file.</param>
        /// <returns></returns>
        public static List<List<string>> ReadDelimtedFile(string filePath, 
            char delimter)
        {
            var lines = new List<List<string>>();

            var fileLines = File.ReadAllLines(filePath);

            foreach (var line in fileLines)
            {
                var lineList = new List<string>();
                lineList.AddRange(line.Split(delimter));
                lines.Add(lineList);
            }

            return lines;
        }

        /// <summary>
        /// Writes the data in linesList into a 
        /// output specificed by path using the delimiter.
        /// If headerList is not null inlcudes the header 
        /// at the top of the file.
        /// </summary>
        /// <param name="path">The path to the file to 
        /// write the delimited file.</param>
        /// <param name="linesList">The contents of the 
        /// file to write out</param>
        /// <param name="headerList">The header line for 
        /// the file, if null no header is included</param>
        /// <param name="delimiter">The delimiter for 
        /// the items in linesList</param>
        public static void WriteDelimtedFile(string path, 
            List<List<string>> linesList, 
            List<string> headerList,
            char delimiter)
        {
            var lines = new List<string>();

            if (headerList != null)
            {
                lines.Add(headerList.Aggregate((i, j) => i + delimiter + j));
            }

            lines.AddRange(linesList.Select(listString => 
                listString.Aggregate((i, j) => i + delimiter + j)));

            File.WriteAllLines(path, lines.ToArray());
        }
    }
}

2 thoughts on “Reading and Writing Delimited Files in .Net Core

Leave a Reply

Your email address will not be published. Required fields are marked *