ItsRaptorman
ItsRaptorman

Reputation: 101

how to fix file .json not found when it is there

I am trying here to consume the data from a json file: DATA.json

[

{"Label"
        
        :"USA",
        "Adress":"This is the us",
        "Lat":"36.9628066",
        "Lng":"-122.0194722"
},
{ "Label"  :"USA",
         "Address":"2020",
          "Lat":"36.9628066", 
          "Lng":"-122.0194722" }

]

Then applying it in my Mainclass:

using System.Collections.Generic;
using Xamarin.Forms.Maps;
using Xamarin.Forms;
using System.IO;
using Newtonsoft.Json;
using System;


namespace Orbage
{
    

class MapPage : ContentPage
    {
        public MapPage()
        {
            CustomMap customMap = new CustomMap
            {
                MapType = MapType.Street

            };
            // ...
            Content = customMap;

            var json = File.ReadAllText("File.json");
            var places = JsonConvert.DeserializeObject<List<File>>(json);
            foreach (var place in places)
            {
                CustomPin pin = new CustomPin
                {
                    Type = PinType.Place,
                    Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
                    Label = place.Label,
                    Address = place.Address,
                    Name = "Xamarin",

                    Url = "http://xamarin.com/about/"
                };



                customMap.CustomPins = new List<CustomPin> { pin };

                customMap.Pins.Add(pin);
                customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
            }
        }
    }


}

But when I put the file in there it says that it doesn't exist. Error: FilenotfoundException Whats the fix for this. I tried: Changing the location of the file. Its name Instead of E:/-/- i even wrote file.json but I still get the same error. Thanks alot!

Upvotes: 2

Views: 705

Answers (2)

Leo Zhu
Leo Zhu

Reputation: 15021

Try to use the method below:

Put your File.json to your PCL project,and set its Build Action to EmbeddedResource.

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("Orbage.File.json");
string text = "";
using (var reader = new System.IO.StreamReader(stream))
     {
       text = reader.ReadToEnd();
     }

Upvotes: 2

Sh.Imran
Sh.Imran

Reputation: 1033

Its better before reading the file, put check whether file exists in the location or not.

if (File.Exists("File.Json"))

With this you would become to know that your given path is correct or not.

Upvotes: 2

Related Questions