简体   繁体   中英

Getting UnauthorizedAccessException when acessing a Xml file via the .load method C#

Currently I have been loading xml files based on user input from a textbox in a UWP app I am making. The app itself is designed to edit existing files while also display it (kind of like a text editor but only changing attributes and not the form of the file)

This all works fine for any file within my H drive (which I think is entirely local) but not from my C drive or any other network drive. Below is the section where I start loading the user's file at the very start of the application.

XmlTextReader reader = new XmlTextReader(fileAddress.Text);
XmlDocument doc = new XmlDocument();
try{
                    
doc.Load(fileAddress.Text);
}
catch (System.UnauthorizedAccessException)
{
Debug.WriteLine("couldn't access file here");
} 

Below is the error code I get without the catch with my C drive which is what I want to know how I can avoid (ie actually access the file)

Access to the path 'C:\Users\x\Documents\XML_Files\IEC_EI_AR_XMLDesign.xml' is denied.

Below is a path that does work (in my D drive) for the same file:

H:\XML_Files\IEC_EI_AR_XMLDesign.xml

I have looked into other posts and they don't seem to help or don't address this specific issue (certain drives working while certain drives not working). I tried these solutions here which seem pretty reasonable but they didn't work or were out of date

I need to save the XML file using linq with xml code in C#

I know that I might be needing to change the permissions of these folders or give Visual Studio/my program heightened permissions to let the user access their own drive though I am not quite sure where/how I could do this. Additionally, any solution I would still want to maintain read/write privileges.

Any advice or suggestions/referals are appreciated!

Found a workaround from the bottom comment of this answer UnauthorizedAccessException on writing XML to a file by saving/storing my files in "C:\Users<username>\AppData\Local\Packages<appname/ identifier>\LocalState"

This allows me to save/edit files in my C Drive (with user permission I guess) though I can now look into expanding these permissions to folders above this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM