首页 文章

通用(UWP)应用程序中的ConfigurationManager和AppSettings

提问于
浏览
19

我想在配置文件中存储API密钥而不将其检入源代码控制,并在我的UWP应用程序中读取数据 .

一个常见的解决方案是将密钥存储在.config文件中(例如 app.configweb.config )并像这样访问它:

var apiKey = ConfigurationManager.AppSettings.Get("apiKey");

我'm working on a Universal Windows (UWP) app and can' t访问保存 ConfigurationManager 的System.Configuration命名空间 .

如何在UWP应用程序中访问AppSettings?或者,在UWP应用程序中访问配置数据的最佳方法是什么?

3 回答

  • -2

    在我的特定用例中,我需要使用未由源代码控制跟踪的外部文件 . 有两种方法可以从资源或配置文件中访问数据 .

    一种是打开并解析配置文件 . 给定一个文件 sample.txtBuild Action ContentCopy to Output Directory 无关紧要),我们可以用

    var uri = new System.Uri("ms-appx:///sample.txt");
    var sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
    

    要么

    var packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    var sampleFile = await packageFolder.GetFileAsync("sample.txt");
    

    其次是

    var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
    

    或者,我们可以使用 Resources . 将新资源项添加到项目中,名为 resourcesFile.resw . 要访问数据,请使用:

    var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
    var token = resources.GetString("secret");
    

    我在博客文章中写了更详细的答案Custom resource files in UWP

  • 13

    我认为你所谓的“ApiKey”是API为你提供生成访问令牌的静态密钥 . 如果是这种情况,也许最好的方法是在源代码控件中创建一个带有该值的静态类,如下所示:

    public static class MyCredentials
    {
        public static string MyApiKey = "apiKey";
    }
    

    然后,您可以从代码中轻松访问该值:

    var myApiKey = MyCredentials.MyApiKey;
    

    如果要将值存储在纯文本文件中,则必须使用 StorageFileFileIO 类手动编写/读取它 .

    相反,如果"ApiKey"表示动态访问令牌,那么最好的解决方案是使用 ApplicationDataContainer ,正如战略所说 .

  • 1

    您无需创建配置文件 . UWP具有存储本地设置/配置的内置解决方案 . 请查看本教程:

    https://msdn.microsoft.com/en-us/library/windows/apps/mt299098.aspx

    使用ApplicationDataContainer,您将能够按键获取值:

    Object value = localSettings.Values["exampleSetting"];
    

相关问题