如何将singles()写入文件

时间:2015-07-22 16:03:44

标签: .net arrays vb.net io stream

出于调试目的,我需要将一个single()数组写入一个新文件,但我找不到任何示例。 由于我正在尝试调试某些内容,因此我不想相信自己的直觉如何做到这一点。 有人能告诉我吗?

这是正确的方法吗? 我很担心我可能会引入错误。

Public Sub WriteSinglesToFile(ByVal uSingles() As Single, ByVal uPath As String)

    Using fs As New FileStream(uPath, FileMode.Create)
        Using bw As New BinaryWriter(fs)
            For Each no In uSingles
                bw.Write(no)
            Next
        End Using
    End Using

End Sub

2 个答案:

答案 0 :(得分:2)

这是一个单行:

Public Sub WriteSinglesToFile(ByVal uSingles() As Single, ByVal uPath As String)
    'The "R" is for "Round-trip". 
    ' It ensures what you read back later matches what you had originally
    File.WriteAllLines(uPath, uSingles.Select(Function(s) s.ToString("R")))
End Sub

如果您想稍后阅读这些内容:

'Assumes file written by above code...
Public Function ReadSinglesFromFile(ByVal uPath As String) As IEnumerable(Of Single)
    Return File.ReadLines(uPath).Select(Function(l) Single.Parse(l))
End Sub

答案 1 :(得分:1)

您可以使用BinaryWriter.Write方法编写单曲

Public Sub WriteSinglesToFile(ByVal uSingles() As Single, ByVal uPath As String)
    Using writer As IO.BinaryWriter = New IO.BinaryWriter(IO.File.Open(uPath, IO.FileMode.Create))
        For Each uVal As Single In uSingles 
            writer.Write(uVal)
        Next
    End Using 
End Sub