0

我正在编写一个 MVC 应用程序,它将数据导出到 CSV 文件。我通过 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
4

2 回答 2

2

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

mStream.Close()

或与

mStream.Flush()

在 WriteStream 之后

于 2013-05-25T03:43:42.287 回答
0

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

Dim sw As New StreamWriter(mStream)
sw.AutoFlush = True
于 2014-03-14T16:52:54.497 回答