-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
SettingsProvider.cs
102 lines (85 loc) · 1.86 KB
/
SettingsProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//************************************************************************************************
// Copyright © 2021 Steven M Cohn. All rights reserved.
//************************************************************************************************
namespace ResxTranslator
{
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
/// <summary>
/// Loads, save, and manages user settings
/// </summary>
internal class SettingsProvider
{
private readonly string path;
private readonly XElement root;
/// <summary>
/// Initialize a new provider.
/// </summary>
public SettingsProvider()
{
var attribute = Assembly.GetExecutingAssembly()
.GetCustomAttributes<AssemblyProductAttribute>()
.FirstOrDefault();
var appData = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
attribute != null ? attribute.Product : "RoboTranslator");
path = Path.Combine(appData, "Settings.xml");
if (File.Exists(path))
{
try
{
root = XElement.Load(path);
}
catch
{
//
}
}
if (root == null)
{
// file not found so initialize with defaults
root = new XElement("settings");
}
}
public string Get(string name)
{
var element = root.Elements(name).FirstOrDefault();
if (element != null)
{
return element.Value;
}
return null;
}
public void Set(string name, string value)
{
var element = root.Elements(name).FirstOrDefault();
if (element == null)
{
root.Add(new XElement(name, value));
}
else
{
element.Value = value;
}
}
public void Save()
{
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
try
{
Directory.CreateDirectory(dir);
}
catch
{
//
}
}
root.Save(path, SaveOptions.None);
}
}
}