Export a C# DataSet to a text file

bobble14988 picture bobble14988 · Aug 24, 2011 · Viewed 60.3k times · Source

There are a lot of examples online of how to fill a DataSet from a text file but I want to do the reverse. The only thing I've been able to find is this but it seems... incomplete?

I want it to be in a readable format, not just comma delimited, so non-equal spacing between columns on each row if that makes sense. Here is an example of what I mean:

Column1          Column2          Column3
Some info        Some more info   Even more info
Some stuff here  Some more stuff  Even more stuff
Bits             and              bobs

Note: I only have one DataTable within my DataSet so no need to worry about multiple DataTables.

EDIT: When I said "readable" I meant human-readable.

Thanks in advance.

Answer

Roy Goode picture Roy Goode · Aug 24, 2011

This should space out fixed length font text nicely, but it does mean it will process the full DataTable twice (pass 1: find longest text per column, pass 2: output text):

    static void Write(DataTable dt, string outputFilePath)
    {
        int[] maxLengths = new int[dt.Columns.Count];

        for (int i = 0; i < dt.Columns.Count; i++)
        {
            maxLengths[i] = dt.Columns[i].ColumnName.Length;

            foreach (DataRow row in dt.Rows)
            {
                if (!row.IsNull(i))
                {
                    int length = row[i].ToString().Length;

                    if (length > maxLengths[i])
                    {
                        maxLengths[i] = length;
                    }
                }
            }
        }

        using (StreamWriter sw = new StreamWriter(outputFilePath, false))
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
            }

            sw.WriteLine();

            foreach (DataRow row in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!row.IsNull(i))
                    {
                        sw.Write(row[i].ToString().PadRight(maxLengths[i] + 2));
                    }
                    else
                    {
                        sw.Write(new string(' ', maxLengths[i] + 2));
                    }
                }

                sw.WriteLine();
            }

            sw.Close();
        }
    }