Windows 程序下添加Persisted 文件

    Window Form 程序通常希望记住上次操作的习惯以便Dialog在下次显示,操作的时候,能很快的给出上次当前用户的操作习惯,以带来更好的用户体验。在次情况下, 通常的做法是把当前用户的数据系列化成xml或者ini文件存储到当前用户的APP Data文件夹下。
    本文显示通过INI文件的方法来描述这一过程。在此之前,必须的又common的ini文件操作类。实例如下:

    public class IniFiles
    {
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

        public static void Write(string section, string key, string val, string filePath)
        {
            WritePrivateProfileString(section, key, val, filePath);
        }

        public static void Write(string section, string key, bool val, string filePath)
        {
            Write(section, key, val.ToString(), filePath);
        }

        public static void Write(string section, string key, int val, string filePath)
        {
            Write(section, key, val.ToString(), filePath);
        }

        public static string Read(string section, string key, string def, string filePath)
        {
            Byte[] buffer = new Byte[65535];
            int bufLen = GetPrivateProfileString(section, key, def, buffer, buffer.GetUpperBound(0), filePath);
            string s = Encoding.UTF8.GetString(buffer);
            s = s.Substring(0, bufLen);
            return s.Trim();
        }

        public static bool Read(string section, string key, bool def, string filePath)
        {
            try
            {
                string v = Read(section, key, def.ToString(), filePath);
                return Convert.ToBoolean(v);
            }
            catch
            {
                return false;
            }
        }

        public static int Read(string section, string key, int def, string filePath)
        {
            try
            {
                string v = Read(section, key, def.ToString(), filePath);
                return Convert.ToInt32(v);
            }
            catch
            {
                return 0;
            }
        }
    }

 

    接下来描述程序中该如何使用此类。

    第一:一般在需要存储的时候调用write 方法。

private const string PERSIST_KEY = "KEY";
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CompnayName\\ApplicationName");
if (!Directory.Exists(path))
    Directory.CreateDirectory(path);
path = string.Format("{0}\\{1}.ini", path, PERSIST_KEY);
IniFiles.Write(PERSIST_KEY, "PATH""Test to persisted", path);

   第二: 在需要读取这些persisted的地方读取。

var perststedSetting = IniFiles.Read(PERSIST_KEY, "PATH""", path)

 

     ini文件是window中一种很常用的文件格式。此文描述了怎样操作ini文件的同时, 也描述了怎么样persisted当前用户的某些信息。

 

posted on 2012-03-27 14:31  Joe.W.Chen  阅读(305)  评论(0编辑  收藏  举报

导航