Solved

Commas in A Streamed CSV

Posted on 2006-06-26
7
550 Views
Last Modified: 2008-02-01
I am streaming a CSV file to the browser.

The problems that I'm presented with are the newline char, and the comma char - both for fairly obvious reasons.

I simply stripped the new line, but I don't want to remove the comma completly. One solution I attempted is to place quotes (both single and double) around the strings within the csv. The quotes are simply interpreted as part of the file, and not something denoting the start and end of a string, so this did not work (I am using a stringbuilder to concat my whole csv together before streaming if that is relevant). The other solution was to replace the comma character with an escaped comma ('\,'), but it's not recognized by VS as a valid escape sequence, and therefore craps out on compile.

Any ideas on how to handle this?

Thanks,
G
0
Comment
Question by:GENTP
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16987823
.NET version?  2002, 2003, or 2005?

Bob
0
 
LVL 5

Author Comment

by:GENTP
ID: 16989041
2002. Framework V 1.1.

Thanks,
G
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 16996728
Where is the data coming from?  A DataTable?

Bob
0
 
LVL 5

Author Comment

by:GENTP
ID: 17076285
It's coming from looping through a SqlDataReader. I could switch the method I use if needed.

G
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 17124757
This is what I use to stream CSV:

Public Class Export

  Private response As HttpResponse

  ' Exports data to a custom format
  Public Sub ExportCSV(ByVal data As DataTable, ByVal fileName As String)

    response = HttpContext.Current.Response

    response.Clear()
    response.ClearHeaders()
    response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
    response.Expires = 1
    response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
    response.Cache.SetValidUntilExpires(False)
    response.CacheControl = "private"
    response.AddHeader("pragma", "cache")

    ' Add the header that specifies the default filename
    ' for the Download/SaveAs dialog
    response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)

    Dim delimiter As String = String.Empty

    response.ContentType = "text/csv"

    Dim exportContent As String = ConvertDataTableToString(data, delimiter)

    If exportContent.Length <= 0 Then
      exportContent = "Error converting data"
    End If

    response.AddHeader("Content-Length", Encoding.UTF8.GetByteCount(exportContent))
    response.BinaryWrite(Encoding.UTF8.GetBytes(exportContent))

    ' Stop execution of the current page.
    response.End()

  End Sub  'ExportCSV

  Public Function ConvertDataTableToString(ByVal sourceData As DataTable, Optional ByVal Delimiter As String = Nothing, Optional ByVal Separator As String = ",") As String

    Dim resultBuilder As StringBuilder
    resultBuilder = New StringBuilder
    resultBuilder.Length = 0

    resultBuilder.Append(ControlChars.Quote)

    ' Add column headers.
    For Each sourceColumn As DataColumn In sourceData.Columns

      If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
        resultBuilder.Append(Delimiter)
      End If

      resultBuilder.Append(sourceColumn.ColumnName)

      If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
        resultBuilder.Append(Delimiter)
      End If

      resultBuilder.Append(Separator)

    Next sourceColumn

    If resultBuilder.Length > Separator.Trim.Length Then
      resultBuilder.Length = resultBuilder.Length - Separator.Trim.Length
    End If

    resultBuilder.Append(ControlChars.Quote)
    resultBuilder.Append(ControlChars.CrLf)

    ' Add data rows.
    For Each rowCurrent As DataRow In sourceData.Rows

      resultBuilder.Append(ControlChars.Quote)

      For Each columnCurrent As DataColumn In sourceData.Columns

        If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
          resultBuilder.Append(Delimiter)
        End If

        resultBuilder.Append(rowCurrent(columnCurrent.ColumnName))

        If Not Delimiter Is Nothing AndAlso (Delimiter.Trim.Length > 0) Then
          resultBuilder.Append(Delimiter)
        End If
        resultBuilder.Append(Separator)

      Next columnCurrent

      resultBuilder.Length = resultBuilder.Length - 1
      resultBuilder.Append(ControlChars.Quote)
      resultBuilder.Append(ControlChars.CrLf)

    Next rowCurrent

    Return resultBuilder.ToString()

  End Function

End Class

Bob
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question