编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

在 C# 中,保存和读取应用程序的默认值(或设置)的多种方法

wxchong 2024-11-12 13:21:59 开源技术 13 ℃ 0 评论

常见的保存方式包括使用 .config 文件、Registry、.ini 文件、JSON 文件、XML 文件、SQLite 数据库等。

1. 使用 .config 文件 (app.config 或 web.config)

// 读取设置
string keyFieldName = Properties.Settings.Default.KeyFieldName;

// 更新并保存设置
Properties.Settings.Default.KeyFieldName = "新姓名";
Properties.Settings.Default.Save();

2. 使用 Windows 注册表 (Registry)

using Microsoft.Win32;

// 保存值到注册表
RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\MyApp");
key.SetValue("KeyFieldName", "新姓名");
key.Close();

// 从注册表读取值
key = Registry.CurrentUser.OpenSubKey(@"Software\MyApp");
string keyFieldName = key.GetValue("KeyFieldName", "默认姓名").ToString();
key.Close();

3. 使用 .ini 文件

使用 P/Invoke 调用 Windows API 来处理 .ini 文件。

using System.Runtime.InteropServices;
using System.Text;

public class IniFile
{
    public string Path;

    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    public IniFile(string iniPath)
    {
        Path = iniPath;
    }

    public void Write(string section, string key, string value)
    {
        WritePrivateProfileString(section, key, value, Path);
    }

    public string Read(string section, string key)
    {
        StringBuilder temp = new StringBuilder(255);
        GetPrivateProfileString(section, key, "", temp, 255, Path);
        return temp.ToString();
    }
}

// 使用示例
IniFile ini = new IniFile(@"C:\path\to\yourfile.ini");

// 写入值
ini.Write("Settings", "KeyFieldName", "新姓名");

// 读取值
string keyFieldName = ini.Read("Settings", "KeyFieldName");

4. 使用 JSON 文件

使用 Newtonsoft.Json 或 System.Text.Json 库来处理 JSON 文件。

using System.IO;
using Newtonsoft.Json;

public class Settings
{
    public string KeyFieldName { get; set; }
}

// 保存设置
Settings settings = new Settings { KeyFieldName = "新姓名" };
File.WriteAllText(@"C:\path\to\settings.json", JsonConvert.SerializeObject(settings));

// 读取设置
Settings loadedSettings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(@"C:\path\to\settings.json"));
string keyFieldName = loadedSettings.KeyFieldName;

5. 使用 XML 文件

using System.IO;
using System.Xml.Serialization;

public class Settings
{
    public string KeyFieldName { get; set; }
}

// 保存设置到 XML 文件
Settings settings = new Settings { KeyFieldName = "新姓名" };
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
using (TextWriter writer = new StreamWriter(@"C:\path\to\settings.xml"))
{
    serializer.Serialize(writer, settings);
}

// 从 XML 文件读取设置
XmlSerializer deserializer = new XmlSerializer(typeof(Settings));
using (TextReader reader = new StreamReader(@"C:\path\to\settings.xml"))
{
    Settings loadedSettings = (Settings)deserializer.Deserialize(reader);
    string keyFieldName = loadedSettings.KeyFieldName;
}

6. 使用 SQLite 数据库

使用 System.Data.SQLite 库来处理 SQLite 数据库。

using System.Data.SQLite;

// 创建 SQLite 数据库连接
using (var connection = new SQLiteConnection("Data Source=settings.db"))
{
    connection.Open();

    // 创建表
    string createTableQuery = "CREATE TABLE IF NOT EXISTS Settings (KeyFieldName TEXT)";
    SQLiteCommand command = new SQLiteCommand(createTableQuery, connection);
    command.ExecuteNonQuery();

    // 插入数据
    string insertQuery = "INSERT INTO Settings (KeyFieldName) VALUES (@KeyFieldName)";
    command = new SQLiteCommand(insertQuery, connection);
    command.Parameters.AddWithValue("@KeyFieldName", "新姓名");
    command.ExecuteNonQuery();

    // 读取数据
    string selectQuery = "SELECT KeyFieldName FROM Settings LIMIT 1";
    command = new SQLiteCommand(selectQuery, connection);
    string keyFieldName = command.ExecuteScalar().ToString();
}

7. 使用 Environment Variables 环境变量

// 设置环境变量
Environment.SetEnvironmentVariable("KeyFieldName", "新姓名", EnvironmentVariableTarget.User);

// 读取环境变量
string keyFieldName = Environment.GetEnvironmentVariable("KeyFieldName", EnvironmentVariableTarget.User);

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表