C# Generating txt file with delimiters

Posted on February 5, 2019 by Suresh Kamrushi in C#

Here sharing code how you can generate/download text file using C#. Below method take following parameters as:
DataTable DT : Is the actual data that need to be write in text file.
String currentFileName : Text file name.
string printHeader : if you want to print header (column name) as a first row of the text file.
string delimiter : delimiter for the text file. It can be “,”, “|” or anything else as per the requirement.

public void GenerateText(DataTable DT, string currentFileName,string printHeader,string delimiter)
{
    try
    {
        MemoryStream ms = new MemoryStream();
        TextWriter tw = new StreamWriter(ms);
        string txtHeader = "";
        string txtBody = "";
        int columnCount = DT.Columns.Count;
        if (printHeader == "yes")
        {
            int count = 0;
            foreach (DataColumn column in DT.Columns)
            {
                count++;
                txtHeader += column.ColumnName;
                if(columnCount != count)
                    txtHeader += delimiter;
            }                    
            txtBody += Environment.NewLine;
        }
        if (DT.Rows.Count > 0)
        {
            foreach (DataRow row in DT.Rows)
            {
                int count = 0;
                foreach (DataColumn column in DT.Columns)
                {
                    count++;
                    txtBody += row[column];
                    if (columnCount != count)
                        txtBody += delimiter;
                }
                txtBody += Environment.NewLine;
            }
        }
        tw.WriteLine(txtHeader+txtBody);
        tw.Flush();
        byte[] bytes = ms.ToArray();
        ms.Close();

        Response.Clear();
        Response.ContentType = "application/force-download";
        Response.AddHeader("content-disposition", "attachment;    filename=" + currentFileName);
        Response.BinaryWrite(bytes);
        Response.End(); 
    }
    catch (Exception e)
    {
        logger.Error("Error generating txt file "+e);
    }
}

You need to include below namespace:

using System.IO;

Hope it helps someone!!!

Tagged as ,