-
Notifications
You must be signed in to change notification settings - Fork 0
/
IniFile.cs
72 lines (60 loc) · 2.2 KB
/
IniFile.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace APRSForwarder
{
class IniFile
{
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern long WritePrivateProfileString(string section, string key, string value, string FilePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
static extern int GetPrivateProfileString(string section, string key, string Default, StringBuilder RetVal, int Size, string FilePath);
private readonly FileInfo FileInfo;
private readonly string exe = Assembly.GetExecutingAssembly().GetName().Name;
private readonly FileAccess fileAccess;
public IniFile(string path = null, FileAccess access = FileAccess.ReadWrite)
{
fileAccess = access;
FileInfo = new FileInfo(path ?? exe);
}
public string Read(string key, string section = null)
{
var RetVal = new StringBuilder(65025);
if (fileAccess != FileAccess.Write)
{
GetPrivateProfileString(section ?? exe, key, "", RetVal, 65025, FileInfo.FullName);
}
else
{
throw new Exception("Can`t read file! No access!");
}
return RetVal.ToString();
}
public void Write(string key, string value, string section = null)
{
if (fileAccess != FileAccess.Read)
{
WritePrivateProfileString(section ?? exe, key, value, FileInfo.FullName);
}
else
{
throw new Exception("Can`t write to file! No access!");
}
}
public void DeleteKey(string key, string section = null)
{
Write(key, null, section ?? exe);
}
public void DeleteSection(string section = null)
{
Write(null, null, section ?? exe);
}
public bool KeyExists(string key, string section = null)
{
return Read(key, section).Length > 0;
}
}
}