C# 如果缺少值,INI读取器在读取时崩溃
我正在尝试使用这个C#INI阅读器C# 如果缺少值,INI读取器在读取时崩溃,c#,wpf,C#,Wpf,我正在尝试使用这个C#INI阅读器 它很好用,我会写 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 S
它很好用,我会写
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.
问题 读取时,如果
ini
文件中缺少[Section]
或键,程序将崩溃
我相信它正在GetPrivateProfileString()
上崩溃
如果我为一个新控件添加一个read
,并且程序使用了缺少值的旧ini
文件,就会发生这种情况。我希望它能够仍然使用一个旧文件,只要忽略值是否丢失,而不是崩溃
我可以使用一个try/catch
,但我不知道我是否想在每次读取
时都这样做,我从文件中得到了大约100个
INI读卡器
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();
}
}
为什么不使用NuGet包INI读取器之一。您可以发布异常详细信息(类型、消息和堆栈跟踪)吗?我不认为GetPrivateProfileString()
本身会引发任何异常,所有错误返回值都是无效的,但如果是,您可以更改Read
方法来捕获此异常,并返回默认或空字符串。@John谢谢,我会看一看。然后请检查堆栈跟踪!此ini读取器不会引发异常,但稍后尝试使用返回的字符串时会引发异常。这与您发布的代码无关,我测试了它。但当然,如果文件中没有该值,则会得到一个空字符串。例如,int.Parse(“”)
将抛出您看到的异常。所以这是你的问题,不是读取文件。请改为尝试int.TryParse()
。@RenéVogt谢谢,我将尝试int.TryParse()
,我对错误发生的位置感到困惑。为什么不使用一个NuGet包INI阅读器呢。您可以发布异常详细信息(类型、消息和堆栈跟踪)吗?我不认为GetPrivateProfileString()
本身会引发任何异常,所有错误返回值都是无效的,但如果是,您可以更改Read
方法来捕获此异常,并返回默认或空字符串。@John谢谢,我会看一看。然后请检查堆栈跟踪!此ini读取器不会引发异常,但稍后尝试使用返回的字符串时会引发异常。这与您发布的代码无关,我测试了它。但当然,如果文件中没有该值,则会得到一个空字符串。例如,int.Parse(“”)
将抛出您看到的异常。所以这是你的问题,不是读取文件。改为试试int.TryParse()
。@reneéVogt谢谢,我会试试int.TryParse()
,我不知道错误发生在哪里。