Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read Json/Text Files from Asset Folder in Xamarin

I have a xamarin app where I need to read from a json file I have added in the Asset folder.

This is how the folder tree is in the solution explorer.

The code being used to read this json file is called from the User class in the Model folder.

This is how I have tried to access this file.

string path = Path.Combine(Directory.GetCurrentDirectory(), "..", "Assets", "data", "User.json");
var assembly = typeof(User).GetType().Assembly;
var stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{"User.json"}");
using (var reader = new StreamReader(stream))
{
    string jsonString = await reader.ReadToEndAsync();
    users = JsonConvert.DeserializeObject<List<User>>(jsonString);
}

The stream variable is null. Please help out.

like image 219
Isaac Ikusika Avatar asked Dec 05 '25 14:12

Isaac Ikusika


1 Answers

First check that you have set User.json file to Buid Action:EmbeddedResource.

then do like below:

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(User)).Assembly;
Stream stream = assembly.GetManifestResourceStream("TravulRecd.Assets.data.User.json");
string jsonString = "";
using (var reader = new System.IO.StreamReader(stream))
  {
     jsonString = reader.ReadToEnd();
  }
like image 159
Leo Zhu - MSFT Avatar answered Dec 08 '25 15:12

Leo Zhu - MSFT