Results 1 to 8 of 8

Thread: [2.0] One function for saving a class to a file

  1. #1

    Thread Starter
    Not NoteMe SLH's Avatar
    Join Date
    Mar 2002
    Location
    192.168.0.1 Preferred Animal: Penguin Reason for errors: Line#38
    Posts
    3,051

    [2.0] One function for saving a class to a file

    I would like to have a function could write to a file any class instance that was passed to it.

    I read up on seralization, but found that it doesn't work with generics.
    Is there any functions/classes in the standard .net library or will I need to write my own stuff.
    I'm thinking a recursive function that enumerates fields/methods of a class and records the values for those in an XML-like file.
    Quotes:
    "I am getting better then you guys.." NoteMe, on his leet english skills.
    "And I am going to meat her again later on tonight." NoteMe
    "I think you should change your name to QuoteMe" Shaggy Hiker, regarding NoteMe
    "my sweet lord jesus. I've decided never to have breast implants" Tom Gibbons
    Have I helped you? Please Rate my posts.


  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] One function for saving a class to a file

    Serialisation is the in-built mechanism. If there is no automatic (read: Microsoft already wrote it) serialisation for the object that you want to serailise then you can and will have to write your own serialisation code. An example of custom serialisation is the ReadXml and WriteXml methods of the DataSet. You could use Reflector to look inside those methods and see how Microsoft do it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: [2.0] One function for saving a class to a file

    here is an example:
    Code:
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    namespace WindowsApplication1
    {
    	[Serializable()] class MyText
    	{
    		public MyText()
    		{
    		}
    		public void saveMe(string path)
    		{
    			Stream str=File.OpenWrite(path);
    			BinaryFormatter bf=new BinaryFormatter();
    			bf.Serialize(str,this);
    		}
    	}
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  4. #4
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: [2.0] One function for saving a class to a file

    Quote Originally Posted by SLH
    I would like to have a function could write to a file any class instance that was passed to it.

    I read up on seralization, but found that it doesn't work with generics.
    Is there any functions/classes in the standard .net library or will I need to write my own stuff.
    I'm thinking a recursive function that enumerates fields/methods of a class and records the values for those in an XML-like file.
    Of course it works with generics. Check your sources mate. I serialize Generics objects all the time and its fine.
    I don't live here any more.

  5. #5

    Thread Starter
    Not NoteMe SLH's Avatar
    Join Date
    Mar 2002
    Location
    192.168.0.1 Preferred Animal: Penguin Reason for errors: Line#38
    Posts
    3,051

    Re: [2.0] One function for saving a class to a file

    Cool, i'll try that first and see how it goes thanks.
    Wish i could remember where i read that because i think it was an MS page!
    Quotes:
    "I am getting better then you guys.." NoteMe, on his leet english skills.
    "And I am going to meat her again later on tonight." NoteMe
    "I think you should change your name to QuoteMe" Shaggy Hiker, regarding NoteMe
    "my sweet lord jesus. I've decided never to have breast implants" Tom Gibbons
    Have I helped you? Please Rate my posts.


  6. #6

    Thread Starter
    Not NoteMe SLH's Avatar
    Join Date
    Mar 2002
    Location
    192.168.0.1 Preferred Animal: Penguin Reason for errors: Line#38
    Posts
    3,051

    Re: [2.0] One function for saving a class to a file

    Ok, i've got my saved class file:
    Code:
    <?xml version="1.0"?>
    <CEffect_OneShot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <GameActions>
        <anyType xsi:type="CDrawCards">
          <Amount>0</Amount>
        </anyType>
      </GameActions>
    </CEffect_OneShot>
    I'm trying to read it in like so: (enumerating all types in my assembly so i can ise one method for all types.

    Code:
    Type[] Types = System.Reflection.Emit.AssemblyBuilder.GetExecutingAssembly().GetTypes();
                List<Type> LTypes = new List<Type>();
                foreach (Type type in Types)
                {
                    bool HasConst = false;
                    ConstructorInfo[] CI = type.GetConstructors();
                    foreach (ConstructorInfo C in CI)
                    {
                        if (C.GetParameters().Length == 0)
                            HasConst = true;
                    }
                    if (!(type.FullName.Contains("Properties.Settings") ||
                         (HasConst == false) ||
                         (type.IsSubclassOf(typeof(System.Windows.Forms.Form))) ||
                         (type.FullName.Contains("RuntimeType"))))
                        LTypes.Add(type);
                }
                XmlSerializer Serializer = new XmlSerializer(LTypes[0].GetType(), LTypes.ToArray());
                FStream = null;
                if (File.Exists("C:\\Temp\\Class.txt"))
                {
                    FStream = File.OpenWrite("C:\\Temp\\Class.txt");
                }
                else
                {
                    FStream = File.Create("C:\\Temp\\Class.txt");
                }
                return Serializer.Deserialize(FStream);
    Trouble is that i get this error on the new XmlSerializer(....) line:
    Code:
    System.RuntimeType is inaccessible due to its protection level. Only public types can be processed.
    There is no class System.RuntimeType in the list of types or the first type given as parameters, so i'm stumped!

    Any explanation as to what's going on would be great - i've tried searching but i've not found anything relevent.
    Quotes:
    "I am getting better then you guys.." NoteMe, on his leet english skills.
    "And I am going to meat her again later on tonight." NoteMe
    "I think you should change your name to QuoteMe" Shaggy Hiker, regarding NoteMe
    "my sweet lord jesus. I've decided never to have breast implants" Tom Gibbons
    Have I helped you? Please Rate my posts.


  7. #7
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403

    Re: [2.0] One function for saving a class to a file

    You're calling .GetType() on LTypes[0], where LTypes is an array of type, which is in essence
    Code:
    Type t = typeof(something);
    t.GetType(); // returns the typeof(t) -- System.RunTimeType


    Try taking the .GetType() off of that line.
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

  8. #8

    Thread Starter
    Not NoteMe SLH's Avatar
    Join Date
    Mar 2002
    Location
    192.168.0.1 Preferred Animal: Penguin Reason for errors: Line#38
    Posts
    3,051

    Re: [2.0] One function for saving a class to a file

    Hehe, that was a bit dumb, thanks for pointing it out!

    I've got a new problem now... i get the following error in the "Serializer.Deserialize(FStream);" line
    <CEffect_OneShot xmlns=''> was not expected.
    See the save/load code below:
    Code:
    public void SaveClass(object ClassToSave)
    {
        Type[] Types = System.Reflection.Emit.AssemblyBuilder.GetExecutingAssembly().GetTypes();
        List<Type> LTypes = new List<Type>();
        foreach(Type type in Types)
        {
            bool HasConst = false;
            ConstructorInfo[] CI = type.GetConstructors();
            foreach (ConstructorInfo C in CI)
            {
                if (C.GetParameters().Length == 0)
                    HasConst = true;
            }
            if(!(type.FullName.Contains("Properties.Settings") || (HasConst == false) || (type.IsSubclassOf(typeof(System.Windows.Forms.Form)))))
                LTypes.Add(type);
        }
        XmlSerializer Serializer = new XmlSerializer(ClassToSave.GetType(),LTypes.ToArray());
        FStream = null;
        if (File.Exists("C:\\Temp\\Class.txt"))
        {
            FStream = File.OpenWrite("C:\\Temp\\Class.txt");
        }
        else
        {
            FStream = File.Create("C:\\Temp\\Class.txt");
        }
    
        Serializer.Serialize(FStream, ClassToSave);
        FStream.Close();
    }
    public object LoadClass(string Path)
    {
        Type[] Types = System.Reflection.Emit.AssemblyBuilder.GetExecutingAssembly().GetTypes();
        List<Type> LTypes = new List<Type>();
        foreach (Type type in Types)
        {
            bool HasConst = false;
            ConstructorInfo[] CI = type.GetConstructors();
            foreach (ConstructorInfo C in CI)
            {
                if (C.GetParameters().Length == 0)
                    HasConst = true;
            }
            if (!(type.FullName.Contains("Properties.Settings") ||
                 (HasConst == false) ||
                 (type.IsSubclassOf(typeof(System.Windows.Forms.Form)))))
                LTypes.Add(type);
        }
        XmlSerializer Serializer = new XmlSerializer(LTypes[0], LTypes.ToArray());
        FStream = null;
        if (File.Exists("C:\\Temp\\Class.txt"))
        {
            FStream = File.OpenRead("C:\\Temp\\Class.txt");
        }
        else
        {
            FStream = File.Create("C:\\Temp\\Class.txt");
        }
        return Serializer.Deserialize(FStream);
    }
    I've not got a clue what's going on here, so any help would be great.
    Quotes:
    "I am getting better then you guys.." NoteMe, on his leet english skills.
    "And I am going to meat her again later on tonight." NoteMe
    "I think you should change your name to QuoteMe" Shaggy Hiker, regarding NoteMe
    "my sweet lord jesus. I've decided never to have breast implants" Tom Gibbons
    Have I helped you? Please Rate my posts.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width