This project has moved. For the latest updates, please go here.

Getting resulting XML for instance of CSD classes

Jul 8, 2009 at 2:24 PM

I am programatically creating instances of my class objects generated via the CSD tool and I wish to save them to an XML configuration file in some instances.  Not sure what the suggested approach for doing such would be but any feedback would be appreciated.

Dec 10, 2009 at 7:43 AM
Edited Dec 13, 2009 at 1:26 AM

Okay, I've written up a quick and dirty example that I hope will guide you in the right direction:

public void DemonstrateProgramaticalConfiguration()
    // Set the path to the configuration file.
    // For the purposes of this example,
    // just create a temporary file
    string tempConfigurationPath = Path.GetTempPath() + Path.GetRandomFileName() + ".config";
        // Create a filemap, then open the configuration.
        // BTW, the file does not need to exist before doing this,
        // it will allow opening a file that doesn't exist, the file
        // will be created upon save if it doesn't already exist.
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = tempConfigurationPath };
        Configuration tmpConfig = ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None );

        // Since our configuration file is entirely empty,
        // we must create and add our section to it first.
        SampleConfigurationSection sampleSection = new SampleConfigurationSection();
        tmpConfig.Sections.Add( "sampleSection", sampleSection );

        // If this was an existing file and the section was
        // already in it, we could retrieve it instead:
        // SampleConfigurationSection sampleSection = tmpConfig.Sections["sampleSection"] as SampleConfigurationSection;

        // Set (or modify) our settings to our likings
        sampleSection.Foo.Baz = "Something";
        sampleSection.Bars.Add( new Bar { Crackle = 3.14F, Snap = false } );
        sampleSection.Bars.Add( new Bar { Crackle = 42F, Snap = true } );

        // Finally, save our changes

        // You can also save to a different file than you opened,
        // using the SaveAs method.
        // tmpConfig.SaveAs( @"Somewhere\else.config" );
    File.Delete( tempConfigurationPath );

Hope that helps!