FileHelpers - WriteStream不写所有要流的数据

时间:2013-05-24 16:20:38

标签: filehelpers

我正在编写一个将数据导出到CSV文件的MVC应用程序。我通过Linq查询获取了一些数据,查询会提取所有正确的记录,但数据并未完全写入流。在我将流返回给用户之前检查流时,我得到部分数据或根本没有数据。

FileHelpers类

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

创建流然后写入流的代码。

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

2 个答案:

答案 0 :(得分:2)

你需要关闭或刷新流,内部.net不要立即写入流,它只是缓冲信息并在缓冲区已满或流关闭时写入它只需添加此行

mStream.Close()

mStream.Flush()

WriteStream之后

答案 1 :(得分:0)

我自己就是这个问题。解决方案是将StreamWriter对象上的AutoFlush属性设置为true。以下应该有效:

Dim sw As New StreamWriter(mStream)
sw.AutoFlush = True