Files
valheim-dashboard/Valheim Dashboard/Settings.cs
2025-08-01 23:28:27 +02:00

86 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Xml;
using System.Xml.Serialization;
namespace Valheim_Dashboard;
public class Settings
{
private static readonly string AppName = "ValheimDashboard";
private static readonly string SettingsFileName = "settings.json";
private static readonly string ConfigPath = CreatePath();
public static string CreatePath()
{
string basePath;
if (OperatingSystem.IsWindows())
{
basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // %AppData%
}
else // Linux
{
basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".config");
}
// Anwendungspfad erstellen
string appPath = Path.Combine(basePath, AppName);
Directory.CreateDirectory(appPath); // Pfad erstellen, falls er nicht existiert
return appPath;
}
public static string SettingsPath()
{
return Path.Combine(ConfigPath, SettingsFileName);
}
public static void SettingsSave(string name, string value)
{
// Vorhandenes JSON lesen (falls existent)
Dictionary<string, string> settings;
if (File.Exists(SettingsPath()))
{
string existingJson = File.ReadAllText(SettingsPath());
settings = JsonSerializer.Deserialize<Dictionary<string, string>>(existingJson) ?? new Dictionary<string, string>();
}
else
{
settings = new Dictionary<string, string>();
}
// Neuen Schlüssel-Wert hinzufügen/überschreiben
settings[name] = value;
// Änderungen speichern
string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(SettingsPath(), json);
}
public static string? SettingsLoad(string name, bool force_reload = false)
{
string filePath = SettingsPath();
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.TryGetProperty(name, out JsonElement nameProperty))
{
return nameProperty.GetString();
}
else
{
return null;
}
}
return null;
}
}