简体   繁体   English

本地存储文件中的访问被拒绝错误

[英]Access denied Error in Local storage file

I'm using local storage file in the format of xml to save favorites. 我正在使用xml格式的本地存储文件来保存收藏夹。 When I add something to that file and immediately try to read that file it shows access denied. 当我向该文件添加内容并立即尝试读取该文件时,它显示访问被拒绝。 I understand that already an write task is going on which prevents the read task. 我知道已经在执行写任务,这阻止了读任务。 I tried to put a manual wait for the task but each time execution time differs and that still shows an error. 我试图手动等待任务,但是每次执行时间不同,仍然显示错误。 How can I handle this? 我该如何处理?

Adding an element to XML file: 向XML文件添加元素:

StorageFile Favdetailsfile = await ApplicationData.Current.LocalFolder.GetFileAsync("FavFile.xml");

var content = await FileIO.ReadTextAsync(Favdetailsfile);

if (!string.IsNullOrEmpty(content))
{
    var _xml = XDocument.Load(Favdetailsfile.Path);

    var _childCnt = (from cli in _xml.Root.Elements("FavoriteItem")
                     select cli).ToList();

    var _parent = _xml.Descendants("Favorites").First();
    _parent.Add(new XElement("FavoriteItem",
    new XElement("Title", abarTitle),
    new XElement("VideoId", abarVideoId),
    new XElement("Image", abarLogoUrl)));
    var _strm = await Favdetailsfile.OpenStreamForWriteAsync();
    _xml.Save(_strm, SaveOptions.None);
}
else if (string.IsNullOrEmpty(content))
{
    XDocument _xml = new XDocument(new XDeclaration("1.0", "UTF-16", null),
        new XElement("Favorites",
        new XElement("FavoriteItem",
        new XElement("Title", abarTitle),
        new XElement("VideoId", abarVideoId),
        new XElement("Image", abarLogoUrl))));
    var _strm = await Favdetailsfile.OpenStreamForWriteAsync();
    _xml.Save(_strm, SaveOptions.None);
}
}

Reading XML file: 读取XML文件:

StorageFile Favdetailsfile = await ApplicationData.Current.LocalFolder.GetFileAsync("FavFile.xml");

var content = await FileIO.ReadTextAsync(Favdetailsfile);
int i=0;
if (!string.IsNullOrEmpty(content))
{
    var xml = XDocument.Load(Favdetailsfile.Path);
    foreach (XElement elm in xml.Descendants("FavoriteItem"))
    {
        FavoritesList.Add(new FavoritesData(i, (string)elm.Element("Image"), (string)elm.Element("Title"), (string)elm.Element("VideoId")));
        i++;
    }

Siva 湿婆

You have to close your stream when you are saving the xml. 保存xml时必须关闭流。 The two blocks of code in the "Adding an element" section above that look like this: 上方“添加元素”部分中的两个代码块如下所示:

var _strm = await Favdetailsfile.OpenStreamForWriteAsync();
_xml.Save(_strm, SaveOptions.None);

should be put into a using block: 应该放在using块中:

using (var _strm = await Favdetailsfile.OpenStreamForWriteAsync())
{
    _xml.Save(_strm, SaveOptions.None);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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