【问题标题】:How does one access embedded solution files in a PCL class如何访问 PCL 类中的嵌入式解决方案文件
【发布时间】:2015-01-06 01:34:55
【问题描述】:

我正在尝试读取与资源一起添加的 PCL 内容文件。理想的用例是一个 REST 服务模拟,我想在其中托管一些 json 文件来测试网络服务。如果服务器不可用,我希望能够读取这些 json 文件作为替代方案,那么我该怎么做才能实现这一目标?

json 文件和 NetworkService 类都在 PCL 中。假设没有其他解决方案是相关的

这是我尝试过的

  • 将mock json文件和文件夹拖到解决方案中
  • 设置构建操作 -> 内容
  • 将复制设置为输出目录 -> 如果更新则复制

这是 NetworkService 后备代码的一部分

var uri = new Uri("ms-appx:///mock/users/" + UserID + "/GET.json");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

我在尝试运行此代码时收到 System.IO.FileNotFoundException。有什么想法我可能做错了吗?我尝试了EmbeddedResource 方法,但也没有用。

【问题讨论】:

  • 如果您需要我添加有关我的问题的更多信息,请告诉我

标签: c# json winrt-xaml portable-class-library win-universal-app


【解决方案1】:

这是一个 EmbeddedResource 方法,目前还算有效,我将投票/标记一个涉及 Build Action > Content 的更好答案,因为这是处理此问题的一种更简洁的方法。解决方案在答案之一here

// the below approach is essential to getting the right assembly
var assembly = typeof(TestClass).GetTypeInfo().Assembly;

// Use this help aid to figure out what the actual manifest resource name is. 
// can be removed later
string[] resources = assembly.GetManifestResourceNames();

// Once you figure out the name from the string array above, pass it in as the argument here.
// . replaces /
Stream stream = assembly.GetManifestResourceStream("TestMockJson.Mock.TestFile.Json");
var sr = new StreamReader(stream);
return sr.ReadToEnd();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多