OpenStreamForReadAsync失败,"参数不正确"从根

时间:2016-04-26 07:24:40

标签: c# win-universal-app

我试图找出加载我包含在资源中的资源的正确方法。还有一些类似的问题(例如Unable to access Asset files in Metro app),但我希望尽可能避免手动构建任意ms-appx:\\\路径。

// The location of everything in my package.
StorageFolder packageLocation = Package.Current.InstalledLocation;
// The folder I want to load a file from
StorageFolder resources = await packageLocation.GetFolderAsync("Resources");

// I can successfully find the file, and then open a stream.
StorageFile file = await resources.GetFileAsync("Default.xml");
Stream streamFromFile = await file.OpenStreamForReadAsync();

// Also, I can just directly open a stream for the file from the folder.
Stream streamFromFolder = await resources.OpenStreamForReadAsync("Default.xml");

// Error: The parameter is incorrect
Stream streamFromRoot = await packageLocation.OpenStreamForReadAsync("Resources/Default.xml")

我尝试了很多组合,包括./Resources/.../Resources/...ms-appx:///Resources/...。为什么它不能从根文件夹中工作?

注意:我还没有验证过,但我觉得我和其他' root'有同样的问题。文件夹,例如ApplicationData.Current.LocalFolder

2 个答案:

答案 0 :(得分:1)

请使用以下语法进行测试。

var file = await packageLocation.GetFileAsync(@"Resources\Default.xml");

或使用流

var stream = await packageLocation.OpenStreamForReadAsync(@"Resources\Default.xml");

答案 1 :(得分:0)

作为Jean-Sebastien提供的答案的后续内容,我想指出一些其他情况,其中斜线很重要。

如果您使用StorageFile.GetFileFromApplicationUriAsync API,则会接受可以使用ms-appx:///作为前缀的URI参数。

var uri = new Uri(@"ms-appx:///Resources\DefaultPickerView.xml");
var file1 = await StorageFile.GetFileFromApplicationUriAsync(uri);

请注意,在创建URI时,反斜杠全部转换为正斜杠。

另一方面,无论我使用什么前缀和斜线组合,我都无法让StorageFile.GetFileFromPathAsync完全工作。但是,GetFileFromPathAsync MSDN documentation表示您无法在路径中使用正斜杠。