Working With Files in Xamarin.Forms

Xamarin.Forms code runs on multiple platforms – each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
- Create a new solution and name it as “ Workingwithfiles.cs”
- Add the following two files into the project
using System.IO;
using System.Reflection;
- Now we have to add a text file to our project, for adding a new file just right click on the solution pane and select the Add-> New File
- We have to create a label to load the contents of the file in it, and set its height.
1var editor = new Label { Text = "loading...", HeightRequest = 300};
- Now we can use the text file, so first step is to load the texfile in to the current context add the following code for that. “”WorkingwithFiles.PCLTextResource.txt”” is the path of the file .
12var assembly = typeof(App).GetTypeInfo().Assembly;Stream stream = assembly.GetManifestResourceStream("WorkingwithFiles.PCLTextResource.txt");
- To load the file we have created a stream type object.
- Now we havae to read the contents from the stream and convert it to the text format , add the following code to do it
123456string text = "";using (var reader = new System.IO.StreamReader (stream)){text = reader.ReadToEnd ();}editor.Text = text;
- Now We Take a Lable so We Display A Heading Text, Following Code For That
1234567891011121314MainPage = new ContentPage{Content = new StackLayout{VerticalOptions = LayoutOptions.Center,Children ={new Label { Text = "Embedded Resource Text File (PCL)",Font = Font.BoldSystemFontOfSize (NamedSize.Medium)}, editor}}};
If you like this tutorial then you can download full copy of the code from github.
Leave a Reply