关于PropertBag的读写问题

写一个小程序,通过网络或者数据库读写得到的内存数据直接显示到图片控件

如果用GDI+或者Windows API是没有问题的,不过偷懒不想那么麻烦,于是用PropertyBag

先试验一下结果立刻就爆了

Private Sub SavePropDemo()
    'Save property
    Dim pb As PropertyBag
    Set pb = New PropertyBag
    Call pb.WriteProperty("Image1", btnOpen.Picture)
    Open App.Path & "\images\button.raw" For Binary As #1
    Put #1, , pb.Contents
    Close #1
End Sub

这是把图片的属性写到二进制文件,下面是读取

Private Sub ReadPropDemo()
    'Read property
    Dim pb As PropertyBag
    Dim a() As Byte
    
    Set pb = New PropertyBag
    Open App.Path & "\images\button.raw" For Binary As #1
    ReDim a(LOF(1) - 1)
    Get #1, , a
    Close #1
    pb.Contents = a()
    btnOpen.Picture = pb.ReadProperty("Image1", Empty)
End Sub

偏偏是pb.Contents = a()处爆无效过程或参数,网上和MSDN苦寻无果,x你x的xx个xx

调试发现从文件读取出来的字节数比pb.Contents多了12个字节,对比发现前面3个long中第二个正好是实际长度

估计是把什么VARIANT都写进去,于是改代码:

Get #1, 13, a

运行成功,没有错误,于是想是否是Put #1, , pb.Contents会把Variant信息写进去呢? 于是调整保存文件的代码

Private Sub SavePropDemo()
    'Save property
    Dim pb As PropertyBag
    Dim a() As Byte 'Put Variant will write data including Length
    Set pb = New PropertyBag
    Call pb.WriteProperty("Image1", btnOpen.Picture)
    a() = pb.Contents
    Open App.Path & "\images\button.raw" For Binary As #1
    Put #1, , a()
    Close #1
End Sub

可惜啊,问题依旧多了12个字节,这不是他x的坑爹吗,观察发现头部是一致的,那12个字节应该是尾部了

对比尾部发现把最后12个字节再写入一遍了,猛然惊觉是文件扩展名的问题,狗x的微软用扩展名识别文件类型

就行Savepicture()一样,于是调整得到最终代码

Private Sub SavePropDemo()
    'Save property
    Dim pb As PropertyBag
    Set pb = New PropertyBag
    Call pb.WriteProperty("Image1", btnOpen.Picture)
    Open App.Path & "\images\button.dat" For Binary As #1
    Put #1, , pb.Contents
    Close #1
End Sub

Private Sub ReadPropDemo()
    'Read property
    Dim pb As PropertyBag
    Dim a() As Byte
    
    Set pb = New PropertyBag
    Open App.Path & "\images\button.dat" For Binary As #1
    ReDim a(LOF(1) - 1)
    Get #1, , a
    Close #1
    pb.Contents = a()
    btnOpen.Picture = pb.ReadProperty("Image1", Empty)
End Sub

至于为什么跳过12个字节读取能够正常运行,至今没有任何组织或个人声明对此次事件负责..


你可能感兴趣的:(关于PropertBag的读写问题)