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

如何在.NET MAUI iOS中获取App.config配置文件?

解决方案

1. 修正App.config的文件属性

将Projectname/Platforms/iOS/App.config的生成操作设置为Content,复制到输出目录设置为如果较新则复制(或始终复制)。确保文件会被正确打包到iOS应用沙盒中。

2. 使用MAUI适配的路径获取代码

替换原有的Path属性实现,MAUI中不再依赖AppDomain的旧逻辑,改用程序集目录结合沙盒路径的方式:

public string ConfigPath
{
    get
    {
        try
        {
            var assembly = Assembly.GetExecutingAssembly();
            var assemblyDir = Path.GetDirectoryName(assembly.Location);
            var configPath = Path.Combine(assemblyDir, "App.config");

            if (!File.Exists(configPath))
                throw new FileNotFoundException("App.config未找到", configPath);

            return configPath;
        }
        catch (Exception ex)
        {
            throw new FileNotFoundException("获取App.config路径失败", ex);
        }
    }
}

3. 排查XML格式错误

报错“Data at the root level is invalid. Line 1, position 1”多数是App.config本身的XML问题:

  • 检查文件开头是否有多余空格、BOM字节标记
  • 确认XML有唯一根节点(比如<configuration>),标签闭合完整
  • 用记事本打开文件,选择“另存为”,编码选UTF-8(不带BOM)后重新保存

4. 备选:嵌入资源读取方案

如果路径方式仍有问题,可将App.config设为嵌入资源读取:

  1. 修改App.config的生成操作为嵌入的资源
  2. 使用以下代码读取内容:
public string GetConfigContent()
{
    var assembly = Assembly.GetExecutingAssembly();
    // 替换为你的项目命名空间,格式:命名空间.Platforms.iOS.App.config
    var resourceName = "YourProjectNamespace.Platforms.iOS.App.config";

    using (var stream = assembly.GetManifestResourceStream(resourceName))
    {
        if (stream == null)
            throw new FileNotFoundException("嵌入的App.config未找到", resourceName);
        
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:45:22