How to handle UnauthorizedAccessException when starting a FileSystemWatcher - c#

I'm getting an error when starting a FileSystemWatcher for a path that contains an inaccessible folder.
The folder is not accessible even by file system, if I try to access it I get a popup message asking me to grant permanent access to my user, this is completely fine but I'd like to handle it in my application to correctly start the watcher.
_watcher = new FileSystemWatcher(_path, _filter)
{
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName
};
_watcher.Changed += new FileSystemEventHandler(OnChanged);
_watcher.Created += new FileSystemEventHandler(OnCreated);
_watcher.Deleted += new FileSystemEventHandler(OnDeleted);
_watcher.Renamed += new RenamedEventHandler(OnRenamed);
_watcher.EnableRaisingEvents = true;
The exception I'm getting is this
UnauthorizedAccessException: Access to the path 'D:\some_folder' is denied.
System.IO.__Error.WinIOError (System.Int32 errorCode, System.String maybeFullPath) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource].HandleError (System.Int32 hr, System.String path) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource].CommonInit () (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource]..ctor (System.String path, System.String originalUserPath, System.String searchPattern, System.IO.SearchOption searchOption, System.IO.SearchResultHandler`1[TSource] resultHandler, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableFactory.CreateFileNameIterator (System.String path, System.String originalUserPath, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.InternalGetFileDirectoryNames (System.String path, System.String userPathOriginal, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.InternalGetDirectories (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.GetDirectories (System.String path) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.UpdateDataAndDispatch (System.IO.DefaultWatcherData data, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.StartDispatching (System.IO.FileSystemWatcher fsw) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.FileSystemWatcher.Start () (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.FileSystemWatcher.set_EnableRaisingEvents (System.Boolean value) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
(wrapper remoting-invoke-with-check) System.IO.FileSystemWatcher.set_EnableRaisingEvents(bool)
The paths exists, it's inside an usb key for which I have read/write permissions, it's only a specific folder which raises the issue.
Is there a way to safely catch this exception and start the watcher?

You could first check the permissions:
public static bool HasWritePermissionOnDir(string path)
{
var writeAllow = false;
var writeDeny = false;
var accessControlList = Directory.GetAccessControl(path);
if (accessControlList == null)
return false;
var accessRules = accessControlList.GetAccessRules(true, true,
typeof(System.Security.Principal.SecurityIdentifier));
if (accessRules ==null)
return false;
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
continue;
if (rule.AccessControlType == AccessControlType.Allow)
writeAllow = true;
else if (rule.AccessControlType == AccessControlType.Deny)
writeDeny = true;
}
return writeAllow && !writeDeny;
}

Related

System.IO.DirectoryNotFoundException: Could not find a parth of the path

I'm working with MRTK in Unity and I'm trying to access the namespace Microsoft.MixedReality in a script, but I get the error that MixedRealty doesn't exist at Microsoft namespace. However, at the MixedReality script all the namespaces are found, which troubles me for not knowing how to access the namespace.
At the same time, I'm getting this error at the console log:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\User\Documents\cummins-loto\Library\PackageCache\com.microsoft.mixedreality.toolkit.foundation#a77cb7137a89-1660746982947\SDK\Experimental\InteractiveElement\Examples\Scripts\CustomStateExample\KeyboardState'.
at System.IO.__Error.WinIOError (System.Int32 errorCode, System.String maybeFullPath) [0x000f7] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.FileSystemEnumerableIterator1[TSource].HandleError (System.Int32 hr, System.String path) [0x00006] in <695d1cc93cca45069c528c15c9fdd749>:0 at System.IO.FileSystemEnumerableIterator1[TSource].CommonInit () [0x00054] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.FileSystemEnumerableIterator1[TSource]..ctor (System.String path, System.String originalUserPath, System.String searchPattern, System.IO.SearchOption searchOption, System.IO.SearchResultHandler1[TSource] resultHandler, System.Boolean checkHost) [0x000d6] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.FileSystemEnumerableFactory.CreateFileNameIterator (System.String path, System.String originalUserPath, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) [0x00009] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.Directory.InternalGetFileDirectoryNames (System.String path, System.String userPathOriginal, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) [0x00000] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.Directory.InternalGetFiles (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) [0x00000] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.Directory.GetFiles (System.String path, System.String searchPattern) [0x0001c] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.DirectoryInfo.GetFiles (System.String searchPattern) [0x0000e] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x00002] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFilesSubdirs(System.Collections.ArrayList,string)
at System.IO.DirectoryInfo.GetFilesSubdirs (System.Collections.ArrayList l, System.String pattern) [0x0002f] in <695d1cc93cca45069c528c15c9fdd749>:0
at System.IO.DirectoryInfo.GetFiles (System.String searchPattern, System.IO.SearchOption searchOption) [0x00017] in <695d1cc93cca45069c528c15c9fdd749>:0
at (wrapper remoting-invoke-with-check) System.IO.DirectoryInfo.GetFiles(string,System.IO.SearchOption)
at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities.FindShaderFolderInPackage () [0x0005f] in C:\Users\User\Documents\cummins loto\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets#52286f91c474-1660746983015\EditorUtilities\OnLoadUtilities.cs:152
at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities.EnsureShaders (System.Boolean bypassIgnore) [0x00001] in C:\Users\User\Documents\cummins-loto\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets#52286f91c474-1660746983015\EditorUtilities\OnLoadUtilities.cs:42
at Microsoft.MixedReality.Toolkit.Utilities.Editor.OnLoadUtilities..cctor () [0x00001] in C:\Users\User\Documents\cummins-loto\Library\PackageCache\com.microsoft.mixedreality.toolkit.standardassets#52286f91c474-1660746983015\EditorUtilities\OnLoadUtilities.cs:23
UnityEditor.EditorAssemblies:ProcessInitializeOnLoadAttributes (System.Type[])
I don't know what do I have to do to fix that error, I've tried reimporting all assets, regenerating project files, moving the script on which I need to access the namespace to another and erasing the Library folder, but hasn't worked. I hope someone knows a solution!
Thanks in advance.

App Crashing after indegrating Audience Network Ads in Unity 2021.3.6f1

i am getting this error when i play the game in editor after integrating Audience network Ads:
Exception: Field currentActivity or type signature not found
UnityEngine._AndroidJNIHelper.GetFieldID (System.IntPtr jclass, System.String fieldName, System.String signature, System.Boolean isStatic) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
UnityEngine.AndroidJNIHelper.GetFieldID (System.IntPtr javaClass, System.String fieldName, System.String signature, System.Boolean isStatic) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
UnityEngine._AndroidJNIHelper.GetFieldID[ReturnType] (System.IntPtr jclass, System.String fieldName, System.Boolean isStatic) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
UnityEngine.AndroidJNIHelper.GetFieldID[FieldType] (System.IntPtr jclass, System.String fieldName, System.Boolean isStatic) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
UnityEngine.AndroidJavaObject._GetStatic[FieldType] (System.String fieldName) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
UnityEngine.AndroidJavaObject.GetStatic[FieldType] (System.String fieldName) (at <9d0861ca66fe45e696ddf3e3a8d9ea41>:0)
AudienceNetwork.AudienceNetworkAds.IsInitialized () (at Assets/AudienceNetwork/Library/AudienceNetworkAds.cs:33)
AudienceNetwork.AudienceNetworkAds.Initialize () (at Assets/AudienceNetwork/Library/AudienceNetworkAds.cs:15)
AudienceNetwork.AdView..ctor (System.String placementId, AudienceNetwork.AdSize size) (at Assets/AudienceNetwork/Library/AdView.cs:114)
AdsManager.LoadBanner () (at Assets/Scripts/AdsManager.cs:27)
AdsManager.Start () (at Assets/Scripts/AdsManager.cs:12)
Snreenshot
Screenshot
Screenshot

Read json file inside a zip file without decompression remotely

I am trying to read a zip file remotly from a url this bit works fine if its from disk but I want to read it remotly without unzipping the file first is that possible or would it make the file inacessable to others?.
public void GetMSFSAddonDetails(string zipFileUrl) {
using (ZipArchive archive = ZipFile.OpenRead(zipFileUrl))
{
var sample = archive.GetEntry("manifest.json");
if (sample != null)
{
using (var zipEntryStream = sample.Open())
{
// serializer = new XmlSerializer(typeof(SampleClass));
/// SampleClass deserialized =
// (SampleClass)serializer.Deserialize(zipEntryStream);
}
}
Edit 2
I am getting the following error when i try to donwload a zip file from the url
This is using android forms with the mainfest
<?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.companyname.msfsaddonshub.forms" android:installLocation="auto">
<uses-sdk android:minSdkVersion="28" android:targetSdkVersion="29" />
<application android:label="MSFSAddonsHub.Forms.Android" android:theme="#style/MainTheme"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.IO.Compression.ZipFile.Open (System.String archiveFileName,
System.IO.Compression.ZipArchiveMode mode) [0x00000] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.cs:81
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.IO.Compression.ZipFile.OpenRead (System.String archiveFileName)
[0x00000] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.cs:39
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
MSFSAddonsHub.BL.MSFSBL.GetMSFSAddonDetails (System.String zipFileUrl)
[0x00001] in
D:\GitMaster\MSFSAddonsHub\MSFSAddonsHub.BL\MSFSAddonsHub.BL\MSFSBL.cs:17
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
MSFSAddonsHub.BL.MSFSBL.DownloadTestFile () [0x00001] in
D:\GitMaster\MSFSAddonsHub\MSFSAddonsHub.BL\MSFSAddonsHub.BL\MSFSBL.cs:13
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
MSFSAddonsHub.Forms.Views.MainMenu..ctor () [0x0001a] in
D:\GitMaster\MSFSAddonsHub\MSFSAddonsHub.Forms\MSFSAddonsHub.Forms\MSFSAddonsHub.Forms\Views\MainMenu.xaml.cs:20
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
(wrapper managed-to-native)
System.Reflection.RuntimeConstructorInfo.InternalInvoke(System.Reflection.RuntimeConstructorInfo,object,object[],System.Exception&)
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object
obj, System.Object[] parameters, System.Boolean wrapExceptions)
[0x00005] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.Reflection/RuntimeMethodInfo.cs:936
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] ---
End of inner exception stack trace --- 01-03 08:10:43.333
F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.Reflection.RuntimeConstructorInfo.InternalInvoke (System.Object
obj, System.Object[] parameters, System.Boolean wrapExceptions)
[0x00018] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/System.Reflection/RuntimeMethodInfo.cs:944
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.RuntimeType.CreateInstanceMono (System.Boolean nonPublic,
System.Boolean wrapExceptions) [0x00095] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/ReferenceSources/RuntimeType.cs:185
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.RuntimeType.CreateInstanceSlow (System.Boolean publicOnly,
System.Boolean wrapExceptions, System.Boolean skipCheckThis,
System.Boolean fillCache) [0x00009] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/corlib/ReferenceSources/RuntimeType.cs:155
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.RuntimeType.CreateInstanceDefaultCtor (System.Boolean
publicOnly, System.Boolean skipCheckThis, System.Boolean fillCache,
System.Boolean wrapExceptions, System.Threading.StackCrawlMark&
stackMark) [0x00027] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/rttype.cs:5770
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.Activator.CreateInstance (System.Type type, System.Boolean
nonPublic, System.Boolean wrapExceptions) [0x00039] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/activator.cs:206
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] at
System.Activator.CreateInstance (System.Type type, System.Boolean
nonPublic) [0x00000] in
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/mscorlib/system/activator.cs:190
01-03 08:10:43.333 F/addonshub.form( 6899): java_vm_ext.cc:570] a
As far as I know the method ZipFile.OpenRead(String) does not handle URLs! It expects an archiveFileName and searches on the disk.
You would probably have to download the zip file and open it afterwards.

Access to path denied (Xamarin/Android)

I am running Windows 10, Visual Studio 2015, and Xamarin. I am rather new to Xamarin (just to set the ground level). I am currently having an issue after I updated recently. My application was working before the update. All my files were read-only, and I had no issues prior the update. Along with that, I have rebuilt the project and I the "clean and rebuild" for the project as well. I have tried it with multiple apps I have, and the other applications do not have this issue. The issue I am getting the following error below.
06-26 13:51:55.108 I/MonoDroid( 6985): UNHANDLED EXCEPTION:
06-26 13:51:55.142 I/MonoDroid( 6985): System.UnauthorizedAccessException: Access to the path "/storage/emulated/0/defaultDirectory/users.ini" is denied.
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x001f1] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.IO.FileOptions options, System.String msgPath, System.Boolean bFromProxy, System.Boolean useLongPath, System.Boolean checkHost) [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,System.IO.FileOptions,string,bool,bool,bool)
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize, System.Boolean checkHost) [0x00067] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, System.Boolean detectEncodingFromByteOrderMarks, System.Int32 bufferSize) [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.StreamReader..ctor (System.String path, System.Boolean detectEncodingFromByteOrderMarks) [0x0000d] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.StreamReader..ctor (System.String path) [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string)
06-26 13:51:55.142 I/MonoDroid( 6985): at System.IO.File.OpenText (System.String path) [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at QykAndroidApp.AdminLoginActivity.decryptUsers () [0x00033] in <65a7af1659a443738d96e6c2b7534ab2>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at QykAndroidApp.AdminLoginActivity.OnCreate (Android.OS.Bundle savedInstanceState) [0x0008a] in <65a7af1659a443738d96e6c2b7534ab2>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x0000f] in <d855bac285f44dda8a0d8510b679b1e2>:0
06-26 13:51:55.142 I/MonoDroid( 6985): at (wrapper dynamic-method) System.Object:28564880-3429-412d-9c61-4f5bb9fc103e (intptr,intptr,intptr)
06-26 13:51:55.153 W/art ( 6985): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable
An unhandled exception occured.
I've read few articles such as (I posted the Google search for the 3rd item because I read almost everything in the top results). I've tried running the program as an administrator and the directory has open access to anyone.
Why is access to the path denied?
System.UnauthorizedAccessException: Access to the path "..." is denied
https://www.google.com/search?q=RegisterNativeMethods%3A+attempt+to+register+0+native+methods+for+android.runtime.JavaProxyThrowable&oq=RegisterNativeMethods%3A+attempt+to+register+0+native+methods+for+android.runtime.JavaProxyThrowable&aqs=chrome..69i57j69i58.572j0j7&sourceid=chrome&ie=UTF-8
For anyone curious on the code of how I am accessing my file, it is below.
private List<string> readUsers()
{
adminUsers = new List<string>();
try
{
StreamReader readerForFile;
//create checks for making sure the card is mounted, the directory is found, and the file is found.
var filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, "defaultDirectory/users.ini");
File.SetAttributes(filePath, FileAttributes.Normal);
if (File.Exists(filePath))
{
//Reads enttire document
//var fillContent = File.ReadAllText(filePath);
readerForFile = File.OpenText(filePath);
if (readerForFile == null) { return null; }
else
{
string line = "";
int counter = 0;
while ((line = readerForFile.ReadLine()) != null)
{
adminUsers.Add(line);
counter++;
}
}
}
}
catch (IOException e)
{
//You'll need to add proper error handling here
alert.SetMessage("File was not found. " + e).SetNeutralButton("Okay", delegate { QuestionActivity.exit(); }).Create().Show();
}
return adminUsers;
}
You should enable READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions in Android.
You can follow this blog to enable the permission in runtime
https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/

Processing Linq XML string

I need to parse XML string with Linq, and I came up with the following code.
using System;
using System.Linq;
using System.Xml.Linq;
class LinqXml
{
public void Parse(string input)
{
XDocument xdoc = XDocument.Load(input);
var lang = from d in xdoc.Elements("PipeUnit").Elements("Step").Elements("Pipelist").Elements("NamedPipe").Elements("NameOfPipe") select d;
Console.WriteLine(lang.First().Value);
foreach (var item in lang)
{
Console.WriteLine(item.Value);
}
}
static void Main()
{
string tempString = #"
<PipeUnit>
<Step>
<Pipelist>
<NamedPipe>
<NameOfPipe>Name</NameOfPipe>
<PipeData>Data</PipeData>
</NamedPipe>
</Pipelist>
</Step>
</PipeUnit>
";
var linqXml = new LinqXml();
linqXml.Parse(tempString);
}
}
When compile this code with Mono - dmcs linqxml.cs /r:System.Xml.Linq.dll, and tried to run, I got the following errors.
Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path "/Users/smcho/Desktop/csharp/
<PipeUnit>
<Step>
<Pipelist>
<NamedPipe>
<NameOfPipe>Name</NameOfPipe>
<PipeData>Data</PipeData>
</NamedPipe>
</Pipelist>
</Step>
<PipeUnit>".
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
at System.Xml.XmlUrlResolver.GetEntity (System.Uri absoluteUri, System.String role, System.Type ofObjectToReturn) [0x00000] in <filename unknown>:0
at Mono.Xml2.XmlTextReader.GetStreamFromUrl (System.String url, System.String& absoluteUriString) [0x00000] in <filename unknown>:0
at Mono.Xml2.XmlTextReader..ctor (Boolean dummy, System.Xml.XmlResolver resolver, System.String url, XmlNodeType fragType, System.Xml.XmlParserContext context) [0x00000] in <filename unknown>:0
at System.Xml.XmlTextReader..ctor (Boolean dummy, System.Xml.XmlResolver resolver, System.String url, XmlNodeType fragType, System.Xml.XmlParserContext context) [0x00000] in <filename unknown>:0
at System.Xml.XmlReader.Create (System.String url, System.Xml.XmlReaderSettings settings, System.Xml.XmlParserContext context) [0x00000] in <filename unknown>:0
at System.Xml.XmlReader.Create (System.String url, System.Xml.XmlReaderSettings settings) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Load (System.String uri, LoadOptions options) [0x00000] in <filename unknown>:0
at System.Xml.Linq.XDocument.Load (System.String uri) [0x00000] in <filename unknown>:0
at LinqXml.Parse (System.String input) [0x00000] in <filename unknown>:0
at LinqXml.Main () [0x00000] in <filename unknown>:0
What might be wrong?
Replace this:
XDocument xdoc = XDocument.Load(input);
with:
XDocument xdoc = XDocument.Parse(input);
you are passing XML, not a file name.
in your Parse method, you want
XDocument.Parse(input)
Replace
XDocument xdoc = XDocument.Load(input);
with
XDocument xdoc = XDocument.Parse(input);

Categories