Reputation: 3
I use Visual Studio 2015 with Xamarin Android.
I want to read some JSON data from file, but I keep getting this System.IO.FileNotFoundException
, even though I have set my files properties "Build: Content, Copy to Output Directory: Copy if newer" and I can see the file physically in my build folder.
I use this code:
var path = @"AedJson.json";
using (var streamReader = new StreamReader(path))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
The exact exception is:
System.IO.FileNotFoundException: Could not find file "/AedJson.json".
Upvotes: 0
Views: 4280
Reputation: 2666
This works using Microsoft.Extensions.Configuration.Json
Set json file build action in properties as embedded resource
Project : Client
FileFolder : Configuration
FileName : appsettings.json
JSON :
{
"Rest": {
"Server": "192.168.0.199",
"Port": "5003"
}
}
CODE:
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;
Upvotes: 0
Reputation: 991
I'm not sure it really is an error, but looking at the error, it seems like the path is incorrect. Do you really need to save your file precisely where you're actually saving it ? If not, try this :
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);
}
Use this path to save and to load. I'm proceeding like this for all my files and it seems to work well.
Upvotes: 0
Reputation: 74174
You need to add your json file to your Xamarin.Android
project as an Asset (within the Assets
folder) and flag it as an AndroidAsset
build type, then you can use the AssetManager
to read it.
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("AedJson.json")))
{
string json = sr.ReadToEnd ();
}
Ref: Using Android Assets
Upvotes: 2