【问题标题】:Xamarin Android System.IO.FileNotFoundException: Could not find file ExceptionXamarin Android System.IO.FileNotFoundException:找不到文件异常
【发布时间】:2016-07-19 09:56:47
【问题描述】:
我将 Visual Studio 2015 与 Xamarin Android 一起使用。
我想从文件中读取一些 JSON 数据,但我一直收到这个 System.IO.FileNotFoundException,即使我已将文件属性设置为“构建:内容,复制到输出目录:如果更新则复制”并且我可以看到该文件物理上在我的构建文件夹中。
我使用这个代码:
var path = @"AedJson.json";
using (var streamReader = new StreamReader(path))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
确切的例外是:
System.IO.FileNotFoundException:找不到文件“/AedJson.json”。
Error Picture
【问题讨论】:
标签:
c#
android
json
xamarin
xamarin.android
【解决方案1】:
您需要将您的 json 文件作为资产添加到您的 Xamarin.Android 项目中(在 Assets 文件夹中)并将其标记为 AndroidAsset 构建类型,然后您可以使用 AssetManager 来读取它。
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("AedJson.json")))
{
string json = sr.ReadToEnd ();
}
参考:Using Android Assets
【解决方案2】:
我不确定这是否真的是一个错误,但查看错误,似乎路径不正确。您真的需要将文件准确地保存在您实际保存的位置吗?如果没有,试试这个:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");
using (var streamReader = new StreamReader(filename))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
使用此路径保存和加载。我对我的所有文件都是这样处理的,它似乎运行良好。
【解决方案3】:
这适用于 Microsoft.Extensions.Configuration.Json
将属性中的 json 文件构建操作设置为嵌入资源
项目:客户
文件文件夹:配置
文件名:appsettings.json
JSON:
{
"Rest": {
"Server": "192.168.0.199",
"Port": "5003"
}
}
代码:
string Namespace = "Client.Configuration";
string FileName = "appsettings.json";
Assembly assembly = GetType().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{Namespace}.{FileName}");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonStream(stream);
var root = configurationBuilder.Build();
IConfigurationSection restClientConfigration = root.GetSection("Rest");
string server = restClientConfigration.GetSection("Server").Value;
string port = restClientConfigration.GetSection("Port").Value;