Saving C# List Into Text File

Introduction

Let say you have got a C# list of objects. You would like to save it into a text file. This function allows you to do it.

Solution

I suppose you have to export the C# array list into the text file. Your class could look like this one,

class Person {
    public int ID {
        get;
        set;
    }
    public string FirstName {
        get;
        set;
    }
    public string Surname {
        get;
        set;
    }
}

Your export data will look like this,

var data = new Person[] {
    new Person() {
            ID = 1, FirstName = "John", Surname = "Smith"
        },
        new Person() {
            ID = 2, FirstName = "Max", Surname = "McDonald"
        }
};

Our function will be the extension method of IEnumerable<T> and generic function.

The extension method should be static and it needs to be created in a static class. Also, the first parameter should be preceded by the keyword "this”. We extend IEnumerable<T> because we would like to use IEnumerable<T> sources like tables, lists, dictionaries. We create generics because we want different classes.

Additionally, the function should have two parameters - fileName and column separator.

static void ExportToTextFile<T>(this IEnumerable<T> data, string FileName, char ColumnSeperator)

Now we need to create the text file. For this, we can use the function File.CreateText. Please remember to surround it by using the statement „(StreamWriter supports IDisposable interface)”. Next, we need to collect the properties info from type T. We ask for the properties info that we can read, property type is a value type or string, and it is not an indexer.

If the property info list contains at least one property info, we can continue. We need to generate the column headers. Use a string.Join function to build the column header from the property info list. Now we can start writing lines of data for every object in our source list.

Firstly, we need to create a generic list of objects for our data.

Secondly, for every property info in the property info list, we collect a value and store it in the list of data.

Thirdly, we build the line using string.Join function and we save it to file.

In the end, we close a file (Dispose method will do it).

Let have fun.

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

namespace ExportToTextFile
{
    class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
    }
    static class Program
    {
        static void Main(string[] args)
        {
            var data = new Person[] {
            new Person() { ID = 1, FirstName = "John", Surname = "Smith" },
            new Person() { ID = 2, FirstName = "Max", Surname = "McDonald" }
            };
            data.ExportToTextFile("person.txt", ';');
        }

        static void ExportToTextFile<T>(this IEnumerable<T> data, string FileName, char ColumnSeperator)
        {
            using (var sw = File.CreateText(FileName))
            {
                var plist = typeof(T).GetProperties().Where(p => p.CanRead && (p.PropertyType.IsValueType || p.PropertyType == typeof(string)) && p.GetIndexParameters().Length == 0).ToList();
                if (plist.Count > 0)
                {
                    var seperator = ColumnSeperator.ToString();
                    sw.WriteLine(string.Join(seperator, plist.Select(p => p.Name)));
                    foreach (var item in data)
                    {
                        var values = new List<object>();
                        foreach (var p in plist) values.Add(p.GetValue(item, null));
                        sw.WriteLine(string.Join(seperator, values));
                    }
                }
            }
        }
    }
}

Summary

We can see that implementing the saving C# list into a text file is not that complicated but just the opposite.