开发者

Best way to do persistence in C Sharp?

I have small number of GUI attribute that i need to save in my application. The attribute are simple ( windows size, window color, ext... ) and they need to be store in file ( can be XML or binary ).

I don't sure i开发者_运维知识库 know what is the fest and best way to write the code ? Is it simple XML or serialization ?

Is there some example ?

Thanks.


Store the value in the web.config file. Here is an example:

<appSettings>
  <add key="size" value="100" />

Edit: Since it looks like its a windows app, an App.config file can be used.


I would recommend to use IsolatedStorage to store application runtime settings:

IsolatedStorageSettings appSettings= IsolatedStorageSettings.ApplicationSettings;
appSettings.Add(<Control.PropertyName>, <Value>);


This is my preferred way of storing application settings, hope it helps

public class Settings
{
    public int WindowWidth { get; set; }

    public int WindowHeight { get; set; }

    public int FullscreenAsDefault { get; set; }
}

then in whichever main class is applicable for the type of application:

    public Settings Settings { get; set; }

    public void OnOpen()
    {
        if ( !File.Exists( "Settings.xml" ) )
        {
            // init settings
            this.Settings = new Settings()
            {
                FullscreenAsDefault = false,
                WindowHeight = 500,
                WindowWidth = 700
            };
        }
        else
        {
            // load settings
            XmlSerializer xmlSerializer = new XmlSerializer( typeof( Settings ) );
            Settings = xmlSerializer.Deserialize( new FileStream( "Settings.xml", FileMode.Open ) ) as Settings;
        }
    }

    public void OnClose()
    {
        // save settings
        XmlSerializer xmlSerializer = new XmlSerializer( typeof( Settings ) );
        xmlSerializer.Serialize( new FileStream( "Settings.xml", FileMode.Create ), this.Settings );
    }


If they're stored as properties in a class, such as Settings you could serialize this to disk (either binary or xml your choice).

Deserialize this file to get your Settings object back when the application starts. If the file doesn't exist, create a new Settings object and serialize the default values.


I would recommend XML because it's "human readable" and can be manipulated/view with normal tools.

The really easy method is to use a DataContractSerializer. The link shows how to define the entity to serialize and how it can be easily serialized. There is also ISerialiazable and XmlSerializer, etc, but why bother when DCS is so easy? :-)


You could go for the plain old INI files, for storing non-sensitive values. You could use Nini (http://nini.sourceforge.net/) to read and write to INI files. .NET framework doesn't provide any inbuilt libraries to handle INI files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜