Exporting data to a CSV, tab delimited or other text format

A question that often comes up in forums is how to export data to a CSV file, or other text format. Here's a method that takes data from a DataReader and writes it to a file.

[C#]

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;

public static void WriteToTextFile(string separator, string filename)
{
  string ConnStr = "Provider=Microsoft.Jet.OleDb.4.0;" +
				"Data Source=|DataDirectory|Northwind.mdb;";
  string query = "SELECT * FROM Customers";
  string sep = separator;

  StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filename));
  using (OleDbConnection Conn = new OleDbConnection(ConnStr))
  {
    using (OleDbCommand Cmd = new OleDbCommand(query, Conn))
    {
      Conn.Open();
      using (OleDbDataReader dr = Cmd.ExecuteReader())
      {
        int fields = dr.FieldCount - 1;
        while (dr.Read())
        {
          StringBuilder sb = new StringBuilder();
          for (int i = 0; i <= fields; i++)
          {
            if (i != fields)
            {
              sep = sep;
            }
            else
            {
              sep = "";
            }
            sb.Append(dr[i].ToString() + sep);

          }
          sw.WriteLine(sb.ToString());
        }
      }
    }
  }
}
[VB]

Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Text
Imports System.Web

Public Shared Sub WriteToTextFile(ByVal separator As String, ByVal filename As String)
  Dim ConnStr As String = "Provider=Microsoft.Jet.OleDb.4.0;" + 
          "Data Source=|DataDirectory|Northwind.mdb;"
  Dim query As String = "SELECT * FROM Customers"
  Dim sep As String = separator

  Dim sw As New StreamWriter(HttpContext.Current.Server.MapPath(filename))
  Using Conn As New OleDbConnection(ConnStr)
    Using Cmd As New OleDbCommand(query, Conn)
    Conn.Open()
      Using dr As OleDbDataReader = Cmd.ExecuteReader()
        Dim fields As Integer = dr.FieldCount - 1
        While dr.Read()
          Dim sb As New StringBuilder()
          Dim i As Integer = 0
          While i <= fields
            If i <> fields Then
              sep = sep
            Else
              sep = ""
            End If
            sb.Append(dr(i).ToString() + sep)
            i += 1
          End While
          sw.WriteLine(sb.ToString())
        End While
      End Using
    End Using
  End Using
End Sub

And in both cases, the method is called by simply passing the separator and filename in as strings:

WriteToTextFile(",", "vfile.txt")

Date Posted:
Last Updated:
Posted by:
Total Views to date: 42986

4 Comments

- Larry Grimes

Why would you EVER write, "sep = sep;"?

C#: if (i == fields) sep = "";VB: If (i = fields) Then sep = ""

NOTE: I ALWAYS use parens to denote identities, it REALLY helps clarify code, even in "If" statements and even if it doesn't seem necessary. It sure helps someone else reading your code!

Maybe, the ONLY time I could see it used is in tertiary commands:

sep = ((i == fields) ? "" : sep);

- Mike

@Larry

Thanks for your comments. You are quite right, of course. At some stage, I might find the time to go over all these older posts and improve the code. A lot of them could do with improvement!

- newbie

Can I just use WriteToTextFile("|", "vfile.txt") when tab delimeted?

- Mike

@newbie

Your separator appears to be a pipe rather than a tab. Tabs are usually \t in C# or vbTab in VB.

Recent Comments

Justin Kusuma 7/24/2015 3:38 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Hi Mike, thanks much for sharing such an article :) Really help me a lot... further, I'd like to...

Michael Easterbrook 7/22/2015 5:35 PM
In response to Inline Razor Syntax Overview
I removed the @ symbols and I am still getting the same error. It only occurs when I have an "if" a...

Sujay 7/22/2015 1:36 PM
In response to ASP.NET MVC, Entity Framework, One-to-Many and Many-to-Many INSERTS
can you explain how to link two tables so that it forms many to many relationship?(Article and...

Max G 7/21/2015 9:29 PM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi, I've opted for this solution in one of my applications but i've found that the apppool is and I...

Michael Easterbrook 7/20/2015 4:31 PM
In response to Inline Razor Syntax Overview
When I have the following code: @foreach (var procRow in procRowDecade) { if (@procRow[3] +...

Shanice 7/18/2015 10:58 PM
In response to A Better Way To Export Gridviews To Excel
Hi. I'm working with mvc. I need to add the above code in the business logic layer, however the...

Matt 7/18/2015 6:29 PM
In response to Nested Layout Pages with Razor
Cheers sir, nice explanation :)...

Keshavan 7/17/2015 9:06 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi Mike, I have followed exactly as illustrated in blog, I get error "StdSchedulerFactory.cs" not...

Paul Thiel 7/16/2015 5:17 PM
In response to ASP.NET 5 By Numbers
Comments Below: "The new version of ASP.NET is called ASP.NET 5. It is a framework for developing...

saket singh 7/16/2015 8:42 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
hi Mike, great tutorial on Quartz.net , but i have One Problem , Everything is working fine as as...