Saving And Reading A Property Bag From Disk
Storing
data in a property bag internally at runtime could probably be useful
on some occations, but what we're interested in is saving the data
while the application is closed. Just like the .frx-files store the
forms non-text contents when the project isn't opened.
Saving a property bag to disk can be done as the following method demonstrates:
- Private Sub SaveContents(Contents As Variant, FilePath As String)
- Dim FileNum As Integer
- FileNum = FileSystem.FreeFile()
- Open FilePath For Binary As FileNum
- Put #FileNum, , Contents
- Close FileNum
- End Sub
The method would be called in the following manner:
- Dim objBag As New PropertyBag
- With objBag
- .WriteProperty "Str", "A string"
- SaveContents .Contents, App.Path & "Things.bag"
- End With
- Set objBag = Nothing
Where objBag.Contents is all the data that the property bag stores, all packed into one messy
Variant-variable.
Now we're got the property bag saved to disk - great! But we still need to be able to read it again, and here's how to do that:
- Private Function LoadContents(FilePath As String) As Variant
- Dim FileNum As Integer
- Dim tempContents As Variant
- FileNum = FileSystem.FreeFile()
- Open FilePath For Binary As FileNum
- Get #FileNum, , tempContents
- Close FileNum
- LoadContents = tempContents
- End Function
The method would be called in the following manner:
- Dim objBag As New PropertyBag
- With objBag
- .Contents = LoadContents(App.Path & "Things.bag")
- Dim Str as String
- Str = objBag.ReadProperty "Str", "There is no value stored in the property bag"
- End With
-
- Set objBag = Nothing
That's really all there is to it!
You
can, as mentioned, also store pictures, fonts, etc.. This without even
changing the way you assign the data to the propertybag. Normally you
would use
Set [Object] = [Object], but you don't have to,
because it of the way it's stored, so the object-files are just handled
as
Variant-type data.
But to extract object-data, such as
picture-files, you need to use the
Set ... =-syntax. Examine the
example project to see how this is done.