C# - 从 JSON 文件中读取

C# - Reading from JSON file

我在读取 JSON 文件时遇到问题。文件被插入到解决方案资源管理器中,生成操作设置为内容,并将 属性 se 复制到始终复制。我希望该文件应该可以从 LocalFolder 中的应用程序访问。

Stream localFolder = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("sources.json");

string json;

using (StreamReader streamReader = new StreamReader(localFolder))
{
    json = streamReader.ReadToEnd();
}

return JsonConvert.DeserializeObject<List<SourceDefinition>>(json);

它返回的错误是:

Error: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

只需尝试 File.OpenRead - 您可能正在尝试从 AppData 打开,这是 thr userprofile 中的一个特殊路径(在本例中为 %localappdata%)

因此 ApplicationData.Current.LocalFolder 指向 users\XXXXX\Local\Packages\YYYYYY\LocalState,其中 XXXX 是用户,YYYY 是您应用的 GUID。据我所知,项目资源管理器中没有文件夹实际指向该位置。您可以尝试使用Windows.ApplicationModel.Package.Current。 InstalledLocation.Path 将使您可以访问应用所在的容器 运行。希望这有帮助。

尝试使用此代码以可扩展的方式读取 json 文件并绑定到列表模型 class

appsettings.json File

    "Mapping": {
        "Column1": {
          "ExcelColumnName": "DISTRIBUTOR UNIQUE ID",
          "DbFieldName": "vehicle_dealer_code",
          "IsRequired": "true",
          "DataType": ""
        },
        "Column1": {
          "ExcelColumnName": "FACTORY ORDER NUMBER",
          "DbFieldName": "vehicle_data02",
          "IsRequired": "true",
          "DataType": ""
        }
    public static T InitOptions<T>(string name, string section) where T : new()
            {
                var config = new ConfigurationBuilder()
                 .SetBasePath(AppContext.BaseDirectory)
                 .AddJsonFile(name, true, true)
                 .Build();
                return config.GetSection(section).Get<T>();
            }

   

    public class Config
        {
            public Mapping Column1 { get; set; }
            public Mapping Column2 { get; set; }        
        }

public class Mapping
{
    public string ExcelColumnName { get; set; }
    public string DbFieldName { get; set; }
    public bool IsRequired { get; set; }
    public string DataType { get; set; }
}

var MappedData = InitOptions<Config>("appsettings.json", "Mapping");