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: Thursday, August 2, 2007 11:41 PM
Last Updated: Thursday, August 2, 2007 11:49 PM
Posted by: Mikesdotnetting
Total Views to date: 37482

4 Comments

Monday, May 3, 2010 2:35 AM - 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);

Monday, May 3, 2010 7:41 AM - 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!

Monday, May 10, 2010 4:12 AM - newbie

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

Tuesday, May 11, 2010 7:45 AM - Mike

@newbie

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

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

stephen 1/28/2015 9:53 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Hi, Sorry for wasting your time, I had a comment <!--Images--> inside the form this stopped it from...

stephen 1/28/2015 9:47 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Everything has been ok up until this part, here's a snippet of the entire file but i removed lines =...

Stephen kenny 1/28/2015 8:26 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Hi, great article. My issue is with the create view. @using (Html.BeginForm("Create", "Reptiles",...

Jenelyn 1/27/2015 6:44 PM
In response to MVC 5 with EF 6 in Visual Basic - Implementing Basic CRUD Functionality
I'm searching CRUD using VB.net 2010 and I can't find any, how sad...

Kadu Portugal 1/23/2015 10:55 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi Mike, Thank you for your useful article. I implement it in my project, and everything run...

Satyabrata 1/23/2015 6:02 AM
In response to Usage of the @ (at) sign in ASP.NET
Refreshed a lot of things.Thanks...

Vo Thanh Chinh Trung 1/22/2015 4:30 PM
In response to Adding A View
It's very helpful...Thank you so much, Mikes!...

Joop Stringer 1/22/2015 12:00 PM
In response to Inline Editing With The WebGrid
How to add a row for a new record ?...

Gaetan C 1/21/2015 8:49 PM
In response to Looking At The WebMatrix WebGrid
I use the webgrid very often and I Wonder if it's possible to merge to different sql query into on...

Teresa 1/19/2015 3:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model
At the top, the first thing you write is "Open Visual Studio and create a new C# Web project named I...