简体   繁体   中英

Xamarin Android System.IO.FileNotFoundException: Could not find file Exception

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".

Error Picture

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM