How to read a text file on Xamarin Forms PCL project?
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");
}
Dpedrinha
Updated on June 05, 2022Comments
-
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 about 8 yearsThanks. 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 about 8 years@Dpedrinha: Do you have this code in the PCL project?
-
Dpedrinha about 8 yearsYes, inside portable project.
-
Giorgi about 8 years@Dpedrinha: Add using System.Reflection;
-
Dpedrinha about 8 yearsThere you go! Thanks! How did you find that out?
-
Giorgi about 8 years@Dpedrinha: VS 2015 suggests missing using statements :)
-
Dpedrinha about 8 yearsLet us continue this discussion in chat.