Saving Custom Data

J

Jonathan Wood

In the past, using either C++ or VB (classic), I routinely stored records of
data as an array of structures, and then simply read and wrote them to and
from a file using basic file operations.

So now I'd like to do something similar with my first .NET application but I
really don't know where to start. I do not feel a database or XML file is
appropriate for this data. I simply want to read and write it to and from a
file in the most efficient manner.

Can anyone offer any examples or tips? Specifically, the questions that are
coming up include:

1. Should I still use structures or am I better off accepting any additional
overhead of using class objects to represent each record?
2. What is the best way to write structures or classes to disk?
3. What is the best way to write a collection of structures or classes to
disk?
4. How come most of the file and try...catch examples I've found seem
absolutely retarded to me? For example, most leave the line that opens the
file (the line most likely to fail) before try, outside of the try block?
What is the point of that?

Thanks.
 
A

Alberto Poblacion

Jonathan Wood said:
1. Should I still use structures or am I better off accepting any
additional overhead of using class objects to represent each record?

I don't think that there's any difference at the time of writing them to
disk. You should choose structures or classes based on how you are going to
use them in your program, not on the need of writing to disk.
2. What is the best way to write structures or classes to disk?

My favourite way is to serialize them. Mark the class or struct with a
[Serializable] attribute and then use a BinaryFormatter to write the
contents to a FileStream.
3. What is the best way to write a collection of structures or classes to
disk?

Make sure that all the objects in the collection are [Serializable] and
apply the preceding method.
4. How come most of the file and try...catch examples I've found seem
absolutely retarded to me? For example, most leave the line that opens the
file (the line most likely to fail) before try, outside of the try block?
What is the point of that?

Maybe they do that because they are writing a Finally block that is
closing the file, so they only want it to execute if the open succeeded. If
it fails, it is caught at a higher level (a try...catch in the routine that
made the call to the ne that is opening the file). I'm not saying that I
like this, just trying to find a logic for the examples that are written in
the way you mention.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top