Save and XDocument to a file in a “using stream”

╄→гoц情女王★ 提交于 2019-12-12 17:13:40

问题


So I'm trying to do the simple task of opening an XML file, adding and XElement to it, and saving it. My curent code doesn't work:

Uri dataUri = new Uri("ms-appx:///XML Files/Pinouts.xml");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
using (var stream = await file.OpenStreamForWriteAsync())
{
    XDocument doc = XDocument.Load(stream);
    doc.Add(new XElement(XElement.Parse(CurrentPinOut)));
    doc.Save(stream);
    stream.Flush();
}

As I get an "Access denied" error. I'm guessing it's a simple fix, but I haven't found anything in the last hour of searching. Any ideas?


回答1:


You cannot write files to InstalledLocation - it's read-only, but you surely can write files to LocalFolder (or other accessible locations):

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Pinouts.xml", CreationCollisionOption.GenerateUniqueName);
using (var stream = await file.OpenStreamForWriteAsync())
{
    XDocument doc = XDocument.Load(stream);
    doc.Add(new XElement(XElement.Parse(CurrentPinOut)));
    doc.Save(stream);
    stream.Flush();
}

More info about application data you will find at MSDN.



来源:https://stackoverflow.com/questions/35090648/save-and-xdocument-to-a-file-in-a-using-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!