Export Dataset/Datatable to CSV File Using C# and VB.NET

watch_later 04 December, 2018
comment 3 Comments


In this article i will show you how to write csv file using dataset/datatable in C# and VB.NET and also explain how you can export dataset/datatble in csv file in c# and vb.net.

while you working with csv and try to write csv files suppose if you have data with comma(,) and double quote("") then may you can't write csv as per your requirement and may your csv will not be generate properly as per your requirement.

Export Dataset/Datatable to CSV File Using C# and VB.NET
Export Dataset/Datatable to CSV File Using C# and VB.NET

There possibility if you working with big data applications and you have lot's of data and clients give you a requirement like they wants to export that all the data in excel but due to too larger data and you may get exception like out of memory exception error, So there is best option is you can write csv file and fixed this issue because csv file able to accept this kind of requirement.

Today i faced same issue in my office actually our client said they need all the data of whole year 2017-2018 with every transaction and its history also,  and i have created stored procedure and return datatable now i have datatable and i directly export that in .xls file and i got error like "Out of Memory Exception Error", and to fixed this issue i have search too many websites on internet but didn't get solution as per my expectation, then my TL said "Nikunj you can try and export that all the data In .CSV file that may helps you" and now i have created one custom method and implemented in my c# code and really that helps me i got a solution as per my requirement.

Now, to overcome this kind of issue here i will show you a custom method that i have created "WriteCSV" in the below article with example.


1) Create DataSet/Datatable
2) Write a Custom Method/Function for Write .CSV file
3) Export Dataset/Datatable to .CSV File.


First, to write csv file we need a dataset/datatable and hear i creating datatable using c# for demonstration, you can get datatable using stored procedure also as per your need.


DataTable GetData()
           DataTable dt = new DataTable();
           dt.Rows.Add(1, "Nikunj Satasiya""Laptop", 37000);
           dt.Rows.Add(2, "Hiren Dobariya""Mouse", 820);
           dt.Rows.Add(3, "Vivek Ghadiya""Pen", 250);
           dt.Rows.Add(4, "Pratik Pansuriya""Laptop", 42000);
           dt.Rows.Add(5, "Sneha Patel""Lip Bam", 130);
           dt.Rows.Add(6, "Jhon Smith""Sigar", 150);
           return dt;


Private Function GetData() As DataTable
        Dim dt As DataTable = New DataTable
        dt.Rows.Add(1, "Nikunj Satasiya""Laptop", 37000)
        dt.Rows.Add(2, "Hiren Dobariya""Mouse", 820)
        dt.Rows.Add(3, "Vivek Ghadiya""Pen", 250)
        dt.Rows.Add(4, "Pratik Pansuriya""Laptop", 42000)
        dt.Rows.Add(5, "Sneha Patel""Lip Bam", 130)
        dt.Rows.Add(6, "Jhon Smith""Sigar", 150)
        Return dt
    End Function

Now We will write a custom function/method to write csv file. 


public static string WriteCSV(string input)
                if (input == null)
                    return string.Empty;
                bool containsQuote = false;
                bool containsComma = false;
                int len = input.Length;
                for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
                    char ch = input[i];
                    if (ch == '"')
                        containsQuote = true;
                    else if (ch == ',')
                        containsComma = true;
                if (containsQuote && containsComma)
                    input = input.Replace("\"""\"\"");
                if (containsComma)
                    return "\"" + input + "\"";
                    return input;


Public Shared Function WriteCSV(ByVal input As StringAs String
            If (input Is NothingThen
                Return String.Empty
            End If
            Dim containsQuote As Boolean = False
            Dim containsComma As Boolean = False
            Dim len As Integer = input.Length
            Dim i As Integer = 0
            Do While ((i < len) _
                        AndAlso ((containsComma = False) _
                        OrElse (containsQuote = False)))
                Dim ch As Char = input(i)
                If (ch = Microsoft.VisualBasic.ChrW(34)) Then
                    containsQuote = True
                ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
                    containsComma = True
                End If
                i = (i + 1)
            If (containsQuote AndAlso containsComma) Then
                input = input.Replace(""""", """""")"if, (containsCommaUnknown, """"" + input + """)
                Return input
            End If
        Catch  As System.Exception
        End Try
    End Function
Now In click of button write following code


private void btnCSV_Click(object sender, EventArgs e)
            StringBuilder sb = new StringBuilder();
            DataTable dt = GetData();
            foreach (DataRow dr in dt.Rows)
                foreach (DataColumn dc in dt.Columns)
                    sb.Append(WriteCSV(dr[dc.ColumnName].ToString()) + ",");
                sb.Remove(sb.Length - 1, 1);
            File.WriteAllText(@"C:\Users\Nikunj-PC\Desktop\Demo\CodingvilaCSV.csv", sb.ToString());
            lblMsg.Text = "Successful";


Private Sub btnCSV_Click(ByVal sender As ObjectByVal e As EventArgs)
        Dim sb As StringBuilder = New StringBuilder
        Dim dt As DataTable = GetData
        For Each dr As DataRow In dt.Rows
            For Each dc As DataColumn In dt.Columns
                sb.Append((WriteCSV(dr(dc.ColumnName).ToString) + ","))
            sb.Remove((sb.Length - 1), 1)
        File.WriteAllText("C:\Users\Nikunj-PC\Desktop\Demo\CodingvilaCSV.csv", sb.ToString)
        lblMsg.Text = "Successful"
    End Sub

If you analyzed the above code then hear I have one CSV file in my desktop location and I want to write that CSV file so I give fixed file path. you can use file open dialog also as per your need as well as also can change the path if you have filed file location.


CSV File
CSV File


This article explains how you can export dataset/datatable to a csv file and also explains how to write a csv file using c# and vb.net.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.


Good example. Thank you! It helped me with a project I am working on. There were some errors with the VB code for the input function. I fixed them in the code below.

Public Shared Function WriteCSV(ByVal input As String) As String
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If

i = (i + 1)
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Return input
End If
Catch ex As Exception
End Try
End Function

delete April 16, 2019 at 1:11 AM

Thank you for your valuable feedback. I will review your code and update the code in the article that you have fixed.

delete April 16, 2019 at 5:46 PM

Please continue this great work and I look forward to more of your awesome blog posts. view

delete March 12, 2021 at 4:49 AM

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon