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

I need to read a text file (Embedded resource) in my Xamarin.Forms PCL project. To work with files, xamarin docs offers 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 cannot find what LoadResourceText is. All I found is that it is a type in my assembly. But I can’t understand what this means.

And I cannot find anywhere a clear practical explanation of what I need to do.

Any help?

thanks

+7
c # xamarin xamarin.forms
source share
1 answer

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

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

If you want to create a file at runtime and read it later, you can use the PCLStorage Library as follows:

 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"); } 
+6
source share

All Articles