Search code examples
c#windows-8microsoft-metrowindows-runtimewinrt-async

GetFilesAsync stops working


I've this piece of code

public static class Storage
{
    public async static Task<bool> Exists(string filename)
    {
        var folder = await Package.Current.InstalledLocation.GetFolderAsync("Assets");
        var _files= await folder.GetFilesAsync(CommonFileQuery.OrderByName).AsTask().ConfigureAwait(false);

        var file = _files.FirstOrDefault(x => x.Name == filename);
        return file != null;
    }
}

and calling it from my Windows 8 Store application;

this.IconExists = this.Game != null && Storage.Exists(this.IconName).Result;

So if I put a break point on the above line and run it step by step, it works, but without breaking and just running the application causes a hang in application.

And a similar code was working on a few days ago's commit;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.Storage.Search;

namespace eggrr.Core.FileStorage
{
    public class Storage
    {
        private IReadOnlyList<StorageFile> _files;

        public Storage()
        {
            _files = GetFilesAsync("Assets").Result;
        }

        private async Task<IReadOnlyList<StorageFile>> GetFilesAsync(string relativeFolderPath)
        {
            var path = string.Format("{0}\\{1}", Package.Current.InstalledLocation.Path, relativeFolderPath);
            var folder = await StorageFolder.GetFolderFromPathAsync(path);
            return await folder.GetFilesAsync(CommonFileQuery.OrderByName).AsTask().ConfigureAwait(false);
        }

        public bool Exists(string filename)
        {
            var file = _files.FirstOrDefault(x => x.Name == filename);
            return file != null;
        }

        private static readonly Storage _instance = new Storage();
        public static Storage Instance { get { return _instance; } }
    }
}

Any ideas?


Solution

  • Seems this solved it issue;

        public static class Storage
    {
        private static IReadOnlyList<StorageFile> _files;
    
        static Storage()
        {
            _files = GetFilesAsync("Assets").Result;
        }
    
        private async static Task<IReadOnlyList<StorageFile>> GetFilesAsync(string relativeFolderPath)
        {
            var folder = await Package.Current.InstalledLocation.GetFolderAsync("Assets").AsTask().ConfigureAwait(false);
            return await folder.GetFilesAsync(CommonFileQuery.OrderByName).AsTask().ConfigureAwait(false);
        }
    
        public static bool Exists(string filename)
        {
            var file = _files.FirstOrDefault(x => x.Name == filename);
            return file != null;
        }
    }
    

    More info on;