System.UnauthorizedAccessException Denied Error - c#

I'm getting the UnauthorizedAccessException when starting up my emulator with my application, it tells me that "Access to /storage/emulated/0/Download/MenuPlayer is denied".
This only occurs when I try to create a file or open up a folder to download files into it.
My AndroidManifest.xml code is:
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
My Code that is trying to access this is:
try {
/// Get the path to the downloads folder
var donwloadDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
path = Path.Combine(donwloadDir.AbsolutePath, dirName);
dirInfo = new DirectoryInfo(path);
///Create a path to the config file folder.
configFilePath = Android.OS.Environment.GetExternalStoragePublicDirectory("").AbsolutePath + "/";
} catch(Exception e) {
Android.Util.Log.Debug(TAG, "STUFF HERE..." + configFilePath);
Android.Util.Log.Debug(TAG, e.Message);
System.IO.File.WriteAllText(#"C:\logs.txt", e.Message);
}
System.IO.File.WriteAllText(#"C:\logs.txt", Android.OS.Environment.DirectoryDownloads);
Android.Util.Log.Debug(TAG, configFilePath);
Android.Util.Log.Debug(TAG, "END | PlayerReader");
the error is:
Unhandled Exception:
System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/Download/MenuPlayer" is denied. occurred

Even if you have enabled READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permission in manifest, you might need to do few things explicitly in code. Are you doing that already?
See post below for details
Xamarin-System.UnauthorizedAccessException: Access to the path is denied
Hope this helps

Related

.net maui poject cannot archive/Publish due to app icon

Following the changes as directed in Microsoft documentation, I made changes to my project as thus.
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true"
android:icon="#mipmap/kigoo"
android:roundIcon="#mipmap/kigoo_round"
android:supportsRtl="true">
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<queries>
<intent>
<action android:name="android.intent.action.DIAL" />
<data android:scheme="tel"/>
</intent>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
</queries>
</manifest>
In the project.csprog
<!-- App Icon -->
<MauiIcon Include="Resources\AppIcon\appicon.svg"
ForegroundFile="Resources\AppIcon\kigoo.svg" ForegroundScale="0.65" Color="#512BD4"
/>
I can deploy to the emulator and physical devices fine but...
Trying to the archive on debug mode (Just to get the errors), fails and does not show any error.
archiving in the release mode throws the following errors:
1.
Severity Code Description Project File Line Suppression State
Error APT2260 resource mipmap/kigoo_round (aka com.companyname.kigoopcmauisimple:mipmap/kigoo_round) not found. This error is likely caused by an issue with the AndroidManifest.xml file or an Android manifest generation attribute in a
source code file. KigooPCMauiSimple C:\Users{path} 1
Severity Code Description Project File Line Suppression State
Error APT2260 resource mipmap/kigoo (aka com.companyname.kigoopcmauisimple:mipmap/kigoo) not found. This error is likely caused by an issue with the AndroidManifest.xml file or an Android manifest generation attribute in a source code file. KigooPCMauiSimple
C:\Users{path} 1
Severity Code Description Project File Line Suppression State
Error APT2067 failed processing manifest. KigooPCMauiSimple C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\32.0.448\tools\Xamarin.Android.Aapt2.targets 212
Please advise, I appreciate it.
I have tested it. You may need to make the following changes in the project.csprog:
<MauiIcon Include="Resources\AppIcon\kigoo.svg"
ForegroundFile="Resources\AppIcon\appicon.svg" ForegroundScale="0.65"
Color="#512BD4"/>
This is because in your Android Manifest file , you have set it like this:
android: icon="#mipmap/kigoo"
So in your project.csprog file, behind MauiIcon.Include attribute, it should also be set accordingly like this:
<MauiIcon Include="Resources\AppIcon\kigoo.svg"/>

Ping Permission denied

When I try to ping a device from my MAUI App built for Android I get a SocketException(Permission Denied). When i build for Windows it works just fine.
I can not find any Permission other than the ones I already have that could be required. Does anyone know what could be causing this?
Tested with Android 11 and Android 12 on physical devices.
EDIT:
Network-connection works fine through HttpClient.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Code:
var sender = new System.Net.NetworkInformation.Ping();
var options = new System.Net.NetworkInformation.PingOptions();
options.DontFragment = true;
string data = "testdata";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 100;
PingReply reply = sender.Send(address, timeout, buffer, options);
Exception:
System.Net.Sockets.SocketException 'Permission denied'

Xamarin forms app is requiring duplicate WRITE_EXTERNAL_STORAGE entries in AndroidManifest

I'm running into a very odd issue in my Xamarin Forms app. I am trying to take a picture in my app, then use OCR to read the text, but I'm struggling to get permissions to be granted for WRITE_EXTERNAL_STORAGE. I now have to declare WRITE_EXTERNAL_STORAGE twice in my AndroidManifest in order for the app to allow me to request storage permissions or to access storage, once as a self-closing tag and once with explicit tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
If either is removed (leaving just one version of WRITE_EXTERNAL_STORAGE), I get the following exception when trying to request permissions for external storage or when trying to capture a picture: "You need to declare using the permission: android.permission.WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml"
This ONLY affects WRITE_EXTERNAL_STORAGE...all other declared permissions (using self-closing tags) in the manifest work appropriately. It's just the write storage permission that needs this "hack."
This issue occurs on emulated devices (debug mode) AND on physical devices (via Play Store alpha track) when only one instance of the permission is listed. When debugging with both lines in the manifest, the app is able to obtain permissions to storage successfully and I can take the picture as expected. The Play Store will not accept submissions with duplicate lines in the manifest, so I am unable to submit to the store using this "hack."
This is a full copy of my AndroidManifest (without PII), including the duplicate lines I have to include in order for storage permissions to be granted successfully when debugging:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="myapp" android:versionName="3.2.2" android:installLocation="auto" android:versionCode="59">
<application android:theme="#android:style/Theme.Material.Light" android:icon="#drawable/Icon120" android:label="MyApp">
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
</manifest>
I also have the following line in my AssemblyInfo.cs file:
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
When I try to request permissions via Xamarin.Essentials or to access the camera to tke a picture via Xamarin.Essentials or CrossMedia, the app blows up with the above exception, claiming I am missing the WRITE_EXTERNAL_STORAGE permission, despite it being in the manifest once (either self-closed or with explicit tag). Any of these lines executing will result in the exception and all lines work when both entries for WRITE_EXTERNAL_STORAGE are present:
var permissionStatus = await Xamarin.Essentials.Permissions.RequestAsync<Xamarin.Essentials.Permissions.StorageWrite>();
var photo = await Xamarin.Essentials.MediaPicker.CapturePhotoAsync(new Xamarin.Essentials.MediaPickerOptions { Title = DateTime.Now.ToString("G") + ".jpg" });
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { Name = DateTime.Now.ToString("G") + ".jpg" });
I have tried updating all of my NuGet packages and am now on the latest versions of frameworks for the app (Xamarin Forms v5 and Xamarin.Essentials 1.6.1) but this issue still persists. I also tried completely deleting the manifest and restarting from scratch, but the same "hack" is still needed.
Has anyone run into this or have any idea of how this can be fixed?
Thank you in advance!
To anyone who has this issue, the solution was to remove all references to and uninstall the NuGet package for HockeySDK.Xamarin. As soon as I removed everything related to this, the issue resolved itself and I no longer had the problem with the manifest

Problem with Xamarin autostart application

I am currently developing an app to use a barcode scanner, one of the requirements is that app autostart with the device.
so, google on that I found some interest thinks, but when I implemented it fails epicly, the app does not starts.
this is mainfest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="AppConsulta.Droid" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="24" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="AppConsulta.Android" android:icon="#drawable/Logo_Jumbo_Cencosud">
<activity android:name="MainActivity" />
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
and this is my receiver
namespace AppConsulta.Droid
{
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted }, Priority = (int)IntentFilterPriority.LowPriority)]
public class BootReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent serviceStart = new Intent(context, typeof(MainActivity));
serviceStart.AddFlags(ActivityFlags.NewTask);
context.StartActivity(serviceStart);
}
}
}
using adb.exe I manage to extract the log of the device
and it shows this
10-22 16:33:00.412 2007 2007 E AndroidRuntime: FATAL EXCEPTION: main
10-22 16:33:00.412 2007 2007 E AndroidRuntime: Process: AppConsulta.Droid, PID: 2007
10-22 16:33:00.412 2007 2007 E AndroidRuntime: java.lang.RuntimeException: Unable to instantiate receiver AppConsulta.Droid.BootReceiver: java.lang.ClassNotFoundException: Didn't find class "AppConsulta.Droid.BootReceiver" on path: DexPathList[[zip file "/data/app/AppConsulta.Droid-1/base.apk"],nativeLibraryDirectories=[/data/app/AppConsulta.Droid-1/lib/arm, /data/app/AppConsulta.Droid-1/base.apk!/lib/armeabi-v7a, /vendor/lib, /system/lib]]

Permission Denial: requires android.permission.READ_PHONE_STATE

I'm trying to detect phone calls in my android app but I receive the following message when receiving a call:
08-23 15:16:04.685 Vodafone VFD 600 Warning 850 BroadcastQueue Permission Denial: receiving Intent { act=android.intent.action.PHONE_STATE flg=0x10 (has extras) } to com....LogCalls requires android.permission.READ_PHONE_STATE due to sender android (uid 1000)
08-23 15:16:04.549 Vodafone VFD 600 Warning 850 BroadcastQueue Permission Denial: receiving Intent { act=android.intent.action.PHONE_STATE flg=0x10 (has extras) } to com....LogCalls requires android.permission.READ_PRIVILEGED_PHONE_STATE due to sender android (uid 1000)
My AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com...." android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="27" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<application android:label="myapp" android:icon="#drawable/logo">
</application>
</manifest>
And my broadcast receiver:
[BroadcastReceiver]
[IntentFilter(new[] {TelephonyManager.ActionPhoneStateChanged,Intent.ActionNewOutgoingCall })]
public class LogCalls : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action == TelephonyManager.ActionPhoneStateChanged)
{
Console.WriteLine("state changed");
}
}
}
What I am missing ?
Firstly, third-party apps are not permitted to acquire the READ_PRIVILEGED_PHONE_STATE permission. See Privileged Permission Whitelisting:
Privileged applications are system applications located in the /system/priv-app directory on the system image. Historically, device implementers had little control over which signature|privileged permissions could be granted to privileged apps. Starting in Android 8.0, implementors can explicitly whitelist privileged apps in the system configuration XML files in the /etc/permissions directory. Apps not explicitly listed in these XML files are not granted privileged permissions.
Secondly, when your app is running on API 23 and above, you'll need to first ask the user to grant you the READ_PHONE_STATE permission at runtime, as it is considered a "dangerous" permission (see Permissions Overview).
You'll need to follow the instructions at Request App Permissions to request the permission from the user at runtime, and only once that permission is granted can your BroadcastReceiver receive the intents.

Categories