I get the next error: System.IO.DirectoryNotFoundException: Could not find a part of the path "/storage/emulated/0/Screenshots/test_picture.jpg".
After testing your code , this error happens in bellow code:
FileStream outStream = new FileStream(file.Path, FileMode.OpenOrCreate);
If using this string root = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
, you should notice that this is a Public external files .
/storage/emulated/0/Documents
From document ,Android apps must be granted permission before they can read or write any public files. So here you need add permissions in AndroidManifest.xml
:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And from android 6.0 , you also need to add runtimer permissions.Here , Suggest that can install Plugin.Permissions NuGet package for project to request a permission.As follow is a example:
OnCreate():
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this,savedInstanceState);
Button Click method():
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
{
//await DisplayAlert("Need location", "Gunna need that location", "OK");
Console.WriteLine("OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
//Best practice to always check that the key exists
if (results.ContainsKey(Permission.Storage))
status = results[Permission.Storage];
}
if (status == PermissionStatus.Granted)
{
string root = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
Java.IO.File myDir = new Java.IO.File(root + "/Screenshots");
myDir.Mkdirs();
string fname = "test_picture.jpg";
Java.IO.File file = new Java.IO.File(myDir, fname);
Console.WriteLine("------root-------" + file.Path);
FileStream outStream = new FileStream(file.Path, FileMode.OpenOrCreate);
....
}
else if (status != PermissionStatus.Unknown)
{
Console.WriteLine("OK");
//await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
}
}
catch (Exception ex)
{
Console.WriteLine("" + ex);
}
Other solution:
If not using Public external files , you can have a try with Private external files
/storage/emulated/0/Android/data/com.companyname.app/files/
This do not need to require a runtime permission.However static permission in AndroidManifest.xml
is also needed.
string root = Application.Context.GetExternalFilesDir("DirectoryPictures").ToString();