You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio运行正常的C#程序,执行文件启动时抛空引用异常

解决Mac Arm64下Avalonia应用读取settings.json失败的问题

问题分析

从错误日志可见,Settings file content: 为空,说明读取到的配置文件内容是空字符串,导致Json反序列化返回null,触发pushSettings方法里的ArgumentNullException。核心原因是sudo运行导致用户上下文切换,以及代码中存在的潜在问题:

  1. 使用sudo运行时,应用切换到root用户,此时Environment.SpecialFolder.MyDocuments指向root用户的Documents目录,而非普通用户的,配置文件路径和调试时不一致。
  2. 路径拼接方式不统一(initLoader用Path.Combine,LoadSettings用字符串拼接),存在跨平台风险。
  3. 未处理反序列化失败的情况,空内容直接反序列化会返回null。

修复步骤

1. 避免用sudo运行应用

桌面应用通常不需要root权限,直接以普通用户身份运行:

./testMacArm642

如果必须使用sudo,需确保root用户的Documents目录有写入权限,或修改配置文件路径到非用户专属目录(如应用安装目录)。

2. 统一路径拼接逻辑

将LoadSettings中的路径拼接改为Path.Combine,同时新增反序列化null的处理:

public void LoadSettings()
{
    try
    {
        string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        // 统一用Path.Combine拼接路径,避免字符串拼接的潜在问题
        string path = Path.Combine(docs, "ContactFinder", "settings.json");
        
        if (!File.Exists(path))
        {
            Console.WriteLine("Settings file not found: " + path);
            throw new FileNotFoundException("Settings file not found", path);
        }

        string json = File.ReadAllText(path);
        Console.WriteLine("Settings file content: " + json);

        Settings set = JsonConvert.DeserializeObject<Settings>(json);
        // 处理反序列化失败的情况,重新生成默认配置
        if (set == null)
        {
            Console.WriteLine("Settings deserialization failed, creating default config.");
            set = new Settings();
            set.restoreDefaults();
            File.WriteAllText(path, JsonConvert.SerializeObject(set));
        }
        pushSettings(set);
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error loading settings: {ex.Message}");
        throw;
    }
}

3. 增强initLoader的异常处理

确保默认配置文件能正确写入,避免因权限问题生成空文件:

public void initLoader()
{
    string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string path = Path.Combine(docs, "ContactFinder");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

    string settingsPath = Path.Combine(path, "settings.json");
    if (!File.Exists(settingsPath))
    {
        try
        {
            Settings set = new Settings();
            set.restoreDefaults();
            File.WriteAllText(settingsPath, JsonConvert.SerializeObject(set));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed to create default settings: {ex.Message}");
            throw;
        }
    }
}

4. 手动验证配置文件

如果问题仍存在,手动检查对应路径下的settings.json:

  • 普通用户路径:~/Documents/ContactFinder/settings.json
  • root用户路径:/var/root/Documents/ContactFinder/settings.json
    若文件为空,手动删除后重新运行应用,让initLoader生成默认配置。

内容的提问来源于stack exchange,提问作者Lito Bezos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 02:19:55