• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 199
  • Last Modified:

How to Determine the Size of a Structure

Hello All,

I need a way to determine the size of a structure, in bytes, so I can use the result in a read statement.

My structure looks something like this

Public Structure MyRec
  Dim MyObj as MyClass
End Structure

I then have a sub in which I want to read MyRec blocks from a file, like this

Private Sub ReadFile()
        Dim objFile As System.IO.File
        Dim fs As System.IO.FileStream
        Dim objMyRec As New MyRec
        fs = objFile.OpenRead(strFileName)
        fs.Read(objMyRec, 0, ???????????????)
End Sub

As I understand it, I need to put the size of what I am reading where the ???????? is above.  If this is right, can someone please tell me how to do this.

  • 2
2 Solutions
you can get the size of a structure through System.Runtime.InteropServices.Marshal.SizeOf(...)

However, I don't think you can save an object like that -- you'll need to serialize it, something like this:

Add this right on the line above the Class definition:

then to save:
Dim myFileStream As New  FileStream("C:\MyFileName.dat",  FileMode.CreateNew)
Dim MyFormatter As New BinaryFormatter()
MyFormatter.Serialize(myFileStream, MyObject)

to read:
Dim myFileStream As New  FileStream("C:\MyFileName.dat",  FileMode.Open)
Dim MyFormatter As New BinaryFormatter()
Dim GenericObject As Object
GenericObject =  MyFormatter.Deserialize(myFileStream)
Dim MyObject As MyObjectType
MyObject = CType(GenericObject, MyObjectType)

(from http://www.fawcette.com/reports/vsliveor/2002/09_18_02/hollis/ )

Does that help?
quiTechAuthor Commented:
thanks, softplus!  

What happens if the file is empty (or EOF reached) on the read?  Is there a way I can check for that?
If your file is damaged (i.e. empty, missing parts, etc) Deserialize will throw an exception (as always, put your code sections between try...catch wrappers) :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now