Я пытаюсь использовать этот C # INI Reader.
https://gist.github.com/Sn0wCrack/5891612
Работает хорошо, я могу написать
INIFile inif = new INIFile(@"C:\Path\To\example.ini");
inif.Write("Example Section", "Example_Key_Text", (vm.Example_Key_Text));
и прочитайте
string example = inif.Read("Example Section", "Example_Key_Text");
Вывод INI-файла:
[Example Section]
Example_Key_Text=This is a test.
Проблема
При чтении программа аварийно завершает работу, если [Section]
или Key
отсутствует в файле ini
.
Я полагаю, что он падает на GetPrivateProfileString()
.
Это происходит, если я добавляю read
для нового элемента управленияи программа использует старый файл ini
, где значение отсутствует.Мне бы хотелось, чтобы он по-прежнему мог использовать старый файл и просто игнорировать, если значение отсутствует вместо сбоя.
Я мог бы использовать try/catch
, но я не знаю, хочу ли я это сделатьна каждом read
у меня их около 100 из файла.
INI Reader
public partial class INIFile
{
public string path { get; private set; }
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
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, this.path);
}
public string Read(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
return temp.ToString();
}
}