![](/img/trans.png)
[英]System.IO.FileNotFoundException: 'Could not find file Xamarin Forms
[英]Xamarin Android System.IO.FileNotFoundException: Could not find file Exception
我將 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”。
您需要將 json 文件作為 Asset(在Assets
文件夾中)添加到Xamarin.Android
項目中,並將其標記為AndroidAsset
構建類型,然后您可以使用AssetManager
讀取它。
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("AedJson.json")))
{
string json = sr.ReadToEnd ();
}
參考: 使用 Android 資產
我不確定這是否真的是錯誤,但查看錯誤,似乎路徑不正確。 您真的需要將文件精確保存在實際保存的位置嗎? 如果沒有,試試這個:
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);
}
使用此路徑保存和加載。 我對我的所有文件都這樣處理,它似乎運行良好。
這使用 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.