0

I am writing an MVC application that will export data to a CSV file. I have some data pulled via a Linq query, and the query pulls all the correct records, but the data is not being completely written to the stream. I get partial or no data at all when I check the stream before it is returned to the user.

The FileHelpers Class

Imports FileHelpers

<DelimitedRecord(",")> _
Public Class AssetSearchFileHelper
    <FieldOrder(1), FieldQuoted()> _
    Public AssetNumber As String

    <FieldOrder(2), FieldQuoted()> _
    Public AssetDescription As String

    <FieldOrder(3), FieldQuoted()> _
    Public SerialNumber As String

    <FieldOrder(4), FieldQuoted()> _
    Public ClassName As String

    <FieldOrder(5), FieldQuoted()> _
    Public ManufacturerName As String

    <FieldOrder(6), FieldQuoted()> _
    Public ModelName As String

    <FieldOrder(7), FieldQuoted()> _
    Public LocationName As String

    <FieldOrder(8), FieldQuoted()> _
    Public AssignedTo As String
End Class

The code that creates the stream and then writes to it.

Dim asfhTemp As List(Of AssetSearchFileHelper) = (From a In lstFilteredAssets
                                                       Select New AssetSearchFileHelper With { _
                                                           .AssetNumber = a.AssetNumber, _
                                                           .AssetDescription = a.AssetDescription, _
                                                           .SerialNumber = a.SerialNumber, _
                                                           .ClassName = a.ClassName, _
                                                           .ManufacturerName = a.ManufacturerName, _
                                                           .ModelName = a.ModelName, _
                                                           .LocationName = a.LocationName, _
                                                           .AssignedTo = a.UserFullName}).ToList()
Dim dle As New DelimitedFileEngine(GetType(AssetSearchFileHelper))
Dim mStream As New MemoryStream

dle.HeaderText = """Asset #"",""Type"",""Serial #"",""Class"",""Make"",""Model"",""Location"",""Assigned To"""

Dim sw As New StreamWriter(mStream)

dle.WriteStream(sw, asfhTemp)
mStream.Position = 0
crimsonisland
  • 21
  • 1
  • 4

2 Answers2

2

You need to Close or Flush the stream, internally .net don't write to the stream right away, it just buffer the info and write it when buffer is full or when stream is close just add this line

mStream.Close()

or with

mStream.Flush()

After the WriteStream

Marcos Meli
  • 3,468
  • 24
  • 29
0

Just had this problem myself. The solution is to set the AutoFlush property on the StreamWriter object to true. The following should work:

Dim sw As New StreamWriter(mStream)
sw.AutoFlush = True
IHateATMFees
  • 346
  • 3
  • 11