Xamari.Forms how can we earn our local files?
Create a new demo.txt file, fill with something and save that. Save this file to the Desktop, if we need this, earn this easy.
Open the Visual Studio and create a Xamarin.Forms portable project (named as: LocalFileSystem).
The files are copied to the appropriate platforms as follows:
UWP: Into the root, just pull it into the LocalFileSystem.UWP. Click on the file (demo.txt). If we don’t see the Properties tab we have to Click on the View Menu->Property Window. So, if we see the Properties tab, change the Build Action to Contect and the Copy to Output Directory to Copy Always.
iOS: Copy to the Resourses and change the Build Action to BundleResource and the Copy to Output Directory do not change.
Android: Copy to the Resourses and change the Build Action to AndroidAsset and the Copy to Output Directory do not change.
Path of the file: the filename except on Android. Here we need to add to the interface implementation this little snippet:
string dbPath = GetLocalFilePath(filename);
CopyDatabaseIfNotExists(dbPath, filename);
And the implementation of two functions:
private static void CopyDatabaseIfNotExists(string dbPath, string filenam)
{
if (!File.Exists(dbPath))
{
using (var br = new BinaryReader(Android.App.Application.Context.Assets.Open(filenam)))
{
using (var bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int length = 0;
while ((length = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, length);
}
}
}
}
}
public static string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string dbPath = Path.Combine(path, filename);
return dbPath;
}
With this method we can achieve any type of file without the code would be established.