How to read a text file on Xamarin Forms PCL project?

10,539

To read an existing file you need to replace LoadResourceText with a class that you have in your PCL project. It is used to get the assembly that contains the embedded file. You will also need to replace WorkingWithFiles with the namespace of your PCL project.

You need to add using System.Reflection; for the code to compile.

If you want to create a file at runtime and read it later you can use PCLStorage Library like this:

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");
}
Share:
10,539
Dpedrinha
Author by

Dpedrinha

Updated on June 05, 2022

Comments

  • Dpedrinha
    Dpedrinha about 2 years

    I need to read a text file (Embedded resource) on my Xamarin.Forms PCL project. On the working with files xamarin docs it suggests this code:

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

    The problem is that I can't find what this LoadResourceText is. All I found is that it's a type in my Assembly. But I can't really understand what it means.

    And I can't find anywhere a clear practical explanation of what I need to do.

    Any help?

    Thanks

  • Dpedrinha
    Dpedrinha about 8 years
    Thanks. I need to load an existing embedded resource file. If I change LoadResourceText with any class in my project it complains that "Type does not contain a definition for GetTypeInfo(). I'm looking at the sample project from the docs and LoadResourceText doesn't implement it too. It's just a normal ContentPage. Any idea?
  • Giorgi
    Giorgi about 8 years
    @Dpedrinha: Do you have this code in the PCL project?
  • Dpedrinha
    Dpedrinha about 8 years
    Yes, inside portable project.
  • Giorgi
    Giorgi about 8 years
    @Dpedrinha: Add using System.Reflection;
  • Dpedrinha
    Dpedrinha about 8 years
    There you go! Thanks! How did you find that out?
  • Giorgi
    Giorgi about 8 years
    @Dpedrinha: VS 2015 suggests missing using statements :)
  • Dpedrinha
    Dpedrinha about 8 years