简体   繁体   中英

Windows 10 UWP App XElement.Save() "Access is denied" exception

I'm writing a Windows 10 UWP App, and I'm hitting a snag. I have a Settings.xml in the root of the app folder that I will use to store the DB connection information, as well as a few ancillary settings. I can load the XML fine, and my function to edit works (I can extract the XML through debug and see the changes). My problem comes when trying to write the edited file. I understand that I don't have direct access to the file system with UWP, however I've tried several different methods I've found online to work within my constraints and still can't find one that works. I always come back with an "Access is denied" error in some form or another. Here is a snippet of what my Save function looks like right now. Any help would be greatly appreciated.

try
{
    XElement xmlSettings = XElement.Load(uri: "Settings.xml");
    XElement xmlNode;

    //Do Stuff (clipped for brevity).

    StorageFolder folder = ApplicationData.Current.LocalFolder;
    StorageFile file = await folder.CreateFileAsync(desiredName: "Settings.xml", options: CreationCollisionOption.ReplaceExisting);
    Stream stream = await file.OpenStreamForWriteAsync();
    xmlSettings.Save(stream);

    Error = "";
}
catch (Exception e)
{
    Error = "SaveSettings";
}

I added an xml file to my solution (in the root) and copy pasted your code. It runs the first time, but gets the exception the second time. The reason is that your stream is not closed. You should use it with using:

using (Stream stream = await file.OpenStreamForWriteAsync())
{
    xmlSettings.Save(stream);
}

With this change the code worked even the second time.

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