1

我正在使用 xml 格式的本地存储文件来保存收藏夹。当我向该文件添加内容并立即尝试读取该文件时,它显示访问被拒绝。我知道已经有一个写任务正在进行,它阻止了读任务。我试图手动等待任务,但每次执行时间不同,仍然显示错误。我该如何处理?

向 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);
}
}

读取 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++;
    }

湿婆

4

1 回答 1

1

保存 xml 时必须关闭流。上面“添加元素”部分中的两个代码块如下所示:

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

应该放入一个using块中:

using (var _strm = await Favdetailsfile.OpenStreamForWriteAsync())
{
    _xml.Save(_strm, SaveOptions.None);
}
于 2013-10-14T23:36:43.767 回答