Best way to store data locally in .NET (C#)

后端 未结 19 1472
南方客
南方客 2020-11-28 01:53

I\'m writing an application that takes user data and stores it locally for use later. The application will be started and stopped fairly often, and I\'d like to make it save

19条回答
  •  青春惊慌失措
    2020-11-28 02:12

    I recommend XML reader/writer class for files because it is easily serialized.

    Serialization in C#

    Serialization (known as pickling in python) is an easy way to convert an object to a binary representation that can then be e.g. written to disk or sent over a wire.

    It's useful e.g. for easy saving of settings to a file.

    You can serialize your own classes if you mark them with [Serializable] attribute. This serializes all members of a class, except those marked as [NonSerialized].

    The following is code to show you how to do this:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Drawing;
    
    
    namespace ConfigTest
    { [ Serializable() ]
    
        public class ConfigManager
        {
            private string windowTitle = "Corp";
            private string printTitle = "Inventory";
    
            public string WindowTitle
            {
                get
                {
                    return windowTitle;
                }
                set
                {
                    windowTitle = value;
                }
            }
    
            public string PrintTitle
            {
                get
                {
                    return printTitle;
                }
                set
                {
                    printTitle = value;
                }
            }
        }
    }
    

    You then, in maybe a ConfigForm, call your ConfigManager class and Serialize it!

    public ConfigForm()
    {
        InitializeComponent();
        cm = new ConfigManager();
        ser = new XmlSerializer(typeof(ConfigManager));
        LoadConfig();
    }
    
    private void LoadConfig()
    {     
        try
        {
            if (File.Exists(filepath))
            {
                FileStream fs = new FileStream(filepath, FileMode.Open);
                cm = (ConfigManager)ser.Deserialize(fs);
                fs.Close();
            } 
            else
            {
                MessageBox.Show("Could not find User Configuration File\n\nCreating new file...", "User Config Not Found");
                FileStream fs = new FileStream(filepath, FileMode.CreateNew);
                TextWriter tw = new StreamWriter(fs);
                ser.Serialize(tw, cm);
                tw.Close();
                fs.Close();
            }    
            setupControlsFromConfig();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

    After it has been serialized, you can then call the parameters of your config file using cm.WindowTitle, etc.

提交回复
热议问题