通用 (UWP) 应用程序中的 ConfigurationManager 和 AppSettings [英] ConfigurationManager and AppSettings in universal (UWP) app
问题描述
我想将 API 密钥存储在配置文件中而不将其签入源代码管理,并在我的 UWP 应用中读取数据.
I would like to store an API key in a configuration file without checking it into source control, and read the data in my UWP app.
一种常见的解决方案是将密钥存储在 .config 文件(例如 app.config
或 web.config
)中并像这样访问它:
A common solution is to store the key in .config file (such as app.config
or web.config
) and access it like so:
var apiKey = ConfigurationManager.AppSettings.Get("apiKey");
我正在开发通用 Windows (UWP) 应用,但无法访问包含 ConfigurationManager
的 System.Configuration 命名空间.
I'm working on a Universal Windows (UWP) app and can't access the System.Configuration namespace that holds ConfigurationManager
.
如何在 UWP 应用中访问 AppSettings?或者,在 UWP 应用中访问配置数据的最佳方式是什么?
How can I access AppSettings in UWP app? Alternatively, what's the best way to access configuration data in an UWP app?
推荐答案
在我的特定用例中,我需要使用源代码管理未跟踪的外部文件.有两种方法可以从资源或配置文件中访问数据.
In my specific use case I needed to use an external file that is not tracked by source control. There are two ways to access data from resource or configuration files.
一个是打开并解析一个配置文件.给定文件 sample.txt
和 Build Action Content
(复制到输出目录 无关紧要),我们可以用
One is to open and parse a configuration file. Given a file sample.txt
with Build Action Content
(Copy to Output Directory doesn't matter), we can read it with
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);
或者,我们可以使用资源.向项目中添加一个名为 resourcesFile.resw
的新资源项.要访问数据,请使用:
Alternatively, we can use Resources. Add a new Resource item to the project, called resourcesFile.resw
. To access data, use:
var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
var token = resources.GetString("secret");
我在博客文章中写了更详细的答案自定义资源文件在 UWP 中
I wrote more verbose answer in a blog post Custom resource files in UWP
这篇关于通用 (UWP) 应用程序中的 ConfigurationManager 和 AppSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!