Forum Xamarin.iOS

Can't access json file due to System.UnauthorizedAccessException

Hello, I'm on a Mac and I can't seem to gain access to my json file even though I set the file type to 'read and write' for myself. The path that I placed in was correct but somehow it throws this error ONLY when I'm trying to access it from a xamarin project and not a normal project.
This is the code

public static void read_json(string path)
        {
            string fileName = "/Users/steve/Downloads/city_list.json";

            using (StreamReader r = new StreamReader(fileName))
            {
                string json = r.ReadToEnd();
                List<City_Data> items = JsonConvert.DeserializeObject<List<City_Data>>(json);

                foreach (City_Data item in items)
                {
                    // For example: {"Sydney": 289102...}
                    var key = item.name;
                    var value = item.id;
                    dict.Add(key, value);
                }
            }

This is part of the json file:

[
  {
    "id": 833,
    "name": "Ḩeşār-e Sefīd",
    "state": "",
    "country": "IR",
    "coord": {
      "lon": 47.159401,
      "lat": 34.330502
    }
  },
...
]
Tagged:

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    An iOS project can only access its own project catalog and its local storage. It can't read the file which is located on Mac's download folder.
    Try to put it directly under the project perhaps resources:

    And then access it through this path:

    string filePath = NSBundle.MainBundle.PathForResource("test.plist", null);
    var text = File.ReadAllText(filePath);
    
Sign In or Register to comment.