如何检查settings.txt文件是否存在?空引用异常排查
问题分析与解决方案
核心问题拆解
你的空引用异常不是因为文件不存在,而是因为:
- 构造函数仅保证配置文件被创建,但新文件是空的,没有你要读取的key,所以
GetKey返回null - 调用
radiobutton1.Trim()时,null对象调用方法触发空引用异常 - 异常提示的“settings.txt不存在”大概率是误导——要么是文件被锁定导致无法读取,要么是异常堆栈的关联错误,实际根源是
null调用方法
紧急修复:解决空引用异常
先修改GetBool方法,先判断返回值是否为null或空字符串,再调用Trim():
private bool GetBool(string keyname) { string value = optionsfile.GetKey(keyname); bool result = false; // 这里可以设置你需要的默认值,比如true if (!string.IsNullOrEmpty(value)) { bool.TryParse(value.Trim(), out result); } return result; }
为什么构造函数检查了还出问题?
构造函数的逻辑只是确保文件存在,但不会自动为你初始化要读取的key。当文件是刚创建的空文件时,GetKey遍历所有行找不到匹配的key,就会返回null,这才是问题的核心,和文件是否存在完全无关。
优化OptionsFile类的潜在问题
你的OptionsFile类还有几个可以修复的隐患,这些也可能导致类似的异常提示:
1. 资源未正确释放,导致文件锁定
当前GetKey和SetKey方法直接创建StreamReader/StreamWriter,没有用using语句管理,容易导致文件被锁定,后续操作时会抛出类似“文件不存在/无法访问”的错误。修改GetKey方法:
public string GetKey(string key) { string keyValue = null; // 使用using自动释放流资源,避免文件锁定 using (StreamReader sr = new StreamReader(Options_File)) { string line; while ((line = sr.ReadLine()) != null) { int equalIndex = line.IndexOf("="); if (equalIndex >= 1) { string lineKey = line.Substring(0, equalIndex); if (lineKey == key) { // 用等号位置截取值,比用key长度更稳健 keyValue = line.Substring(equalIndex + 1); // 找到匹配的key后直接退出循环,提升效率 break; } } } } return keyValue; }
2. 路径拼接错误
实例化OptionsFile时的路径拼接可以用Path.Combine避免手动拼接的错误:
private OptionsFile optionsfile = new OptionsFile( Path.Combine(Path.GetDirectoryName(Application.LocalUserAppDataPath), "Settings.txt") );
SetKey方法里的临时目录拼接也存在同样问题,建议改成:
temp_settings_dir = Path.Combine(path_exe, "temp_settings");
3. 初始化默认配置
如果希望程序首次运行时就有默认的配置值,可以给OptionsFile加一个重载的GetKey方法:
public string GetKey(string key, string defaultValue) { string value = GetKey(key); return string.IsNullOrEmpty(value) ? defaultValue : value; }
这样GetBool可以改成:
private bool GetBool(string keyname) { string value = optionsfile.GetKey(keyname, "false"); // 默认值设为false bool result; bool.TryParse(value.Trim(), out result); return result; }
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

