Ama*_*rek 21 c# portable-class-library uwp
我想在配置文件中存储API密钥而不将其检入源代码控制,并在我的UWP应用程序中读取数据.
一个常见的解决方案是将密钥存储在.config文件(例如app.config或web.config)中,并像这样访问它:
var apiKey = ConfigurationManager.AppSettings.Get("apiKey");
Run Code Online (Sandbox Code Playgroud)
我正在使用通用Windows(UWP)应用程序,无法访问持有的System.Configuration命名空间ConfigurationManager.
如何在UWP应用程序中访问AppSettings?或者,在UWP应用程序中访问配置数据的最佳方法是什么?
Ama*_*rek 15
在我的特定用例中,我需要使用未由源代码控制跟踪的外部文件.有两种方法可以从资源或配置文件中访问数据.
一种是打开并解析配置文件.给定一个sample.txt带有Build Action 的文件Content(复制到输出目录无关紧要),我们可以阅读它
var uri = new System.Uri("ms-appx:///sample.txt");
var sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
Run Code Online (Sandbox Code Playgroud)
要么
var packageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var sampleFile = await packageFolder.GetFileAsync("sample.txt");
Run Code Online (Sandbox Code Playgroud)
其次是
var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
Run Code Online (Sandbox Code Playgroud)
或者,我们可以使用资源.将新资源项添加到项目中,名为resourcesFile.resw.要访问数据,请使用:
var resources = new Windows.ApplicationModel.Resources.ResourceLoader("resourcesFile");
var token = resources.GetString("secret");
Run Code Online (Sandbox Code Playgroud)
我在UWP中的自定义资源文件的博客文章中写了更详细的答案