从文件 C# UWP 中读取 JSON [英] Read JSON from file C# UWP

查看:76
本文介绍了从文件 C# UWP 中读取 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我尝试从文件中读取 JSON 时,我都会收到错误消息.如果我尝试这样做:

Every time I'm trying to read JSON from file I get an error. If I trying to do it:

 JObject o1 = JObject.Parse(File.ReadAllText(@"c:\DB.json"));

或者它:

using (StreamReader file = File.OpenText(@"c:\db.json"))
            using(JsonTextReader reader = new JsonTextReader(file))
            {
                JObject o2 = (JObject)JToken.ReadFrom(reader);
            }

我收到这些错误

{"找不到文件 'c:\DB.json'.":"c:\DB.json"}

{"Could not find file 'c:\DB.json'.":"c:\DB.json"}

如果我将 DB.json 复制到 F: 目录错误是:

If i copy DB.json to the F: directory error is:

{"找不到路径 'f:\DB.json' 的一部分."}

{"Could not find a part of the path 'f:\DB.json'."}

我的问题是什么?

推荐答案

虽然我们可以使用 File.ReadAllText 方法File.OpenText 方法 在 UWP 应用中,但对 UWP 中的 path 参数有一些限制.不是所有的路径都可以在这里使用.

Although we can use File.ReadAllText method or File.OpenText method in UWP apps, but there are some restrictions on the path parameter in UWP. Not all the path can be used here.

默认情况下,应用可以访问某些文件系统位置.应用还可以通过文件选择器或声明功能来访问其他位置.

Apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities.

有关详细信息,请参阅文件访问权限.

For more info, please see File access permissions.

对于像c:\DB.json"或f:\DB.json"这样的文件路径,默认情况下无法在 UWP 中访问它们.您可以先使用 FileOpenPicker 获取访问权限,然后将该项目添加到您的应用的 FutureAccessList 以便您的应用可以在将来轻松访问该项目.

For your file path like "c:\DB.json" or "f:\DB.json", they can't be accessed in UWP by default. You can use FileOpenPicker to gain access first, then add that item to your app's FutureAccessList so that your app can readily access that item in the future.

此外,要在 UWP 应用中读取文件,您可以参考 创建、写入和读取文件.

Besides, to read files in UWP apps, you can refer to Create, write, and read a file.

由于默认情况下所有应用程序都可以访问应用程序安装目录和应用程序数据位置,我建议您将 json 文件放置/存储在这两个位置.如果该文件随您的应用程序一起提供并且不需要更改,您可以将它放在您的应用程序安装目录中.为此,您可以在项目中添加文件并将其构建操作设置为内容.但是安装目录中的文件是只读的,如果以后需要更改文件,可以将其存储在应用程序数据位置,例如 ApplicationData.LocalFolder.

As all apps can access application install directory and application data locations by default, I'd suggest you place/store json file in these two locations. If the file is coming with your app and do not need to change, you can place it in your application install directory. To do this, you can add the file in your project and set its Build Action as Content. However files in install directory are read-only, if you need to change the file later, you can store it in application data locations such as ApplicationData.LocalFolder.

这篇关于从文件 C# UWP 中读取 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆