2013-10-14 51 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