0
votes

I am building a Xamarin.Forms project with a PCL, iOS and Android project. One of my requirements is that I have to read a JSON file stored in the platform project (iOS/Android) from the PCL.

How can I do this please? I can't find a solution for this problem. :(

Thank you very much, Nikolai

2

2 Answers

2
votes

If the file that you want to read is embedded in the platform project assembly you can use the following code:

var assembly = typeof(MyPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLTextResource.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream)) {
    text = reader.ReadToEnd ();
}

Make sure that you replace WorkingWithFiles with namespace of your project and PCLTextResource.txt with name of the file.

Check Xamarin documentation at Loading Files Embedded as Resources for more details

If on the other hand you want to create and read/write files at runtime you can use PCLStorage library:

public async Task PCLStorageSample()
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
        CreationCollisionOption.OpenIfExists);
    IFile file = await folder.CreateFileAsync("answer.txt",
        CreationCollisionOption.ReplaceExisting);
    await file.WriteAllTextAsync("42");
}
1
votes

I got it working by using an IoC container.

In my iOS project I have created a ConfigAccess class:

public class ConfigAccess : IConfigAccess
{
    public string ReadConfigAsString()
    {
        return System.IO.File.ReadAllText("config.json");
    }
}

I also had to add the following line to my AppDelegate.cs

SimpleIoc.Default.Register<IConfigAccess, ConfigAccess>();

And in my PCL I am simply asking for a ConfigAccess object during runtime:

var configAccess = SimpleIoc.Default.GetInstance<IConfigAccess>();
var test = configAccess.ReadConfigAsString();