tags:

views:

283

answers:

3

How can I store C# form element attributes (such as position of a textbox) in a file eg. text file? So that when the user opens the form, data is read from the file into the form? I was told I could use an XML config file... can someone please tell me how to do that in C#?

+2  A: 

It probably depends on the level of detail you'd like to save about the properties of the given form element. For example, if you only want to store, say, 6 fixed values roughly corresponding to X,Y for 3 form elements, then using C#'s built in settings would work just great -- Using Settings in C# (MSDN)

On the other hand, if you want to preserve the exact state of a non-fixed number of form elements, you could go a much more complex route and serialize each form element and store it that way. That will easily become very complex very quickly. Just glance at these and you'll see what I mean --

Serializing controls to an external file

Serialization in WCF

T. Stone
+3  A: 

if you don't need the file to be human readable/editable, it's easier to do this in binary.

create a class or struct to hold all the data you want to persist imnto the file, mark it with [Serializable] attribute, and then use following code.

   using (Stream fs = new FileStream(filSpec, FileMode.Create,
                    FileAccess.Write, FileShare.None))
       (new BinaryFormatter()).Serialize(fs, YourClassOrStruct);

To get the class back from the file,

   using (FileStream strm = new FileStream(filSpec,
                        FileMode.Open, FileAccess.Read))
   {
       IFormatter fmtr = new BinaryFormatter();
       object o = fmtr.Deserialize(strm);
       if (!(o is YourClassOrStruct)) return null;
       return o as YourClassOrStruct;
   }

Doing it with XmlSerializer is fine too, but it gets a bit tricky if the class contains any collections, or lists, or other weirdities

Charles Bretana
A: 

You don't need to manually manage a file or hand-roll any serialization code necessarily. In WinForms applications I use Properties.Settings for storing things like the user's chosen theme etc. They are very easy to work with and I like them because they can be strongly typed.

Here's a blog post about how to do it.

You can also store custom types/classes via Settings. So conceivably you could a separate class with properties reflecting the various form elements you want to track and then store that in the user settings. If the number of elements varies you could always use a dictionary or list.

Sean Gough
Sean, the C# settings facility uses an XML config file behind the scenes so technically he would still be using a file (can't help being technical, it's a programming website)
T. Stone
Yes, I am aware of that. What I meant is he doesn't have to manually/explicitly manage the file or hand-roll any serialization code.
Sean Gough