1 回答

TA貢獻(xiàn)1797條經(jīng)驗 獲得超6個贊
我收到下一個錯誤:System.IO.DirectoryNotFoundException:找不到路徑“/storage/emulated/0/Screenshots/test_picture.jpg”的一部分。
測試您的代碼后,此錯誤發(fā)生在以下代碼中:
FileStream outStream = new FileStream(file.Path, FileMode.OpenOrCreate);
如果使用它string root = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;,您應(yīng)該注意到這是一個公共外部文件。
/存儲/模擬/0/文檔
從文檔中可以看出,Android 應(yīng)用程序必須先獲得許可才能讀取或?qū)懭肴魏喂参募K栽谶@里你需要添加權(quán)限AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
而從android 6.0開始,還需要添加runtimer權(quán)限。這里,建議可以安裝Plugin.Permissions NuGet包給項目申請權(quán)限。如下示例:
創(chuàng)建時():
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this,savedInstanceState);
按鈕點擊方法():
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);
}
其他解決方案:
如果不使用公共外部文件,您可以嘗試使用私有外部文件
/storage/emulated/0/Android/data/com.companyname.app/files/
這不需要運行時權(quán)限。但是AndroidManifest.xml也需要靜態(tài)權(quán)限。
string root = Application.Context.GetExternalFilesDir("DirectoryPictures").ToString();
- 1 回答
- 0 關(guān)注
- 163 瀏覽
添加回答
舉報