I have data and want to write into csv file and save it in Phone storage. So i wrote this code to save the file.
string csv = Models.CSVHelper.GetCSV<TigerProgram>(item);
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"data.csv");
using (var writer = File.CreateText(path))
{
writer.Write(csv);
}
I'm not getting any exception so i think file is saved but i can only access in runtime using code which i don't want.I want to save in external storage where i can get file easily.so how can i save file in external storage?
I used dependency Services to get the Download path from Xamarin.android.Created Interface in Xamarin.Forms and implement it in Xamarin.Android then resolved the interface and got the path Like this
var newPath = Path.Combine(DependencyService.Get<IFileSystem>().GetExternalStorage(),
"data1.txt");
using (var writer = File.CreateText(path))
{
writer.Write(csv);
}
I also needed to call this method for permissions in onCreate()
of mainactivity to solve the access denied exception like this
private void CheckAppPermissions()
{
if ((int)Build.VERSION.SdkInt < 23)
{
return;
}
else
{
if (PackageManager.CheckPermission(Manifest.Permission.ReadExternalStorage, PackageName) != Permission.Granted
&& PackageManager.CheckPermission(Manifest.Permission.WriteExternalStorage, PackageName) != Permission.Granted)
{
var permissions = new string[] {
Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage };
RequestPermissions(permissions, 1);
}
}
}
call this in onCreate()
to solve permission error