Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 886
Dpedrinha Avatar asked Apr 19 '16 17:04

Dpedrinha


1 Answers

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");
}
like image 51
Giorgi Avatar answered Nov 09 '22 05:11

Giorgi