我正在使用 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++;
}
湿婆