Sivakumarc
Sivakumarc

Reputation: 33

Access denied Error in Local storage file

I'm using local storage file in the format of xml to save favorites. 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:

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:

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

Upvotes: 1

Views: 818

Answers (1)

chue x
chue x

Reputation: 18803

You have to close your stream when you are saving the 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 (var _strm = await Favdetailsfile.OpenStreamForWriteAsync())
{
    _xml.Save(_strm, SaveOptions.None);
}

Upvotes: 1

Related Questions