2013-10-14 52 views
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++; 
    } 

湿婆

+0

显示一些代码。可能有错误。 – Xyroid

+0

没有代码错误,因为它在一段时间后读取xml它执行得很好。这发生在任务干扰正在运行的任务时,即在写入时读取。 – Sivakumarc

回答

1

您必须关闭流时要保存的XML。在“添加元素”一节中的代码块上面看起来像这样:

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

应放入using块:

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

谢谢你Chue,修好了! – Sivakumarc