Search code examples
c#windowsfilexamluwp

UWP c# creating a file in ApplicationData.Current.LocalFolder returns null


I created an app that needs to store user data in a file that is created on Application start and when I compile it, it shows me this System.IO.FileLoadException: Could not find or load a specific file. (Exception from HRESULT: 0x80131621) and this System.NullReferenceException: Invalid pointer.

When the Application starts it calls the Init() Method before everything.

    public static class FilesManager
    {

        public static StorageFolder ROOT_DIRECTORY, USER_DIRECTORY;
        public static StorageFile FILES_MANAGER_CACHE_FILE;

        public static volatile string FILES_MANAGER_CACHE;
        public static volatile StorageFolder FOLDER;

        public static async Task Init()
        {
            try
            {
                FOLDER = await ApplicationData.Current.LocalFolder.CreateFolderAsync("DashData", CreationCollisionOption.OpenIfExists);
                FOLDER = await ApplicationData.Current.LocalFolder.GetFolderAsync("DashData");
                if (FOLDER == null) Debug.WriteLine("FOLDER IS NULL.");
                FILES_MANAGER_CACHE_FILE = await FOLDER.CreateFileAsync("filesmanageruserdata.json", CreationCollisionOption.OpenIfExists);
                FILES_MANAGER_CACHE_FILE = await FOLDER.GetFileAsync("filesmanageruserdata.json");
                await LoadFilesManagerCacheAsync();
                
                Debug.WriteLine("TEXT: " + FILES_MANAGER_CACHE);
            }
            catch(Exception e)
            {
                Debug.WriteLine("ERROR: " + e.ToString());
            }
        }

        public static async Task LoadFilesManagerCacheAsync()
        {
            FILES_MANAGER_CACHE = await FileIO.ReadTextAsync(FILES_MANAGER_CACHE_FILE); 
        }
        
        public static async Task storeUserData(string content)
        {
            try
            {
                await FileIO.WriteTextAsync(FILES_MANAGER_CACHE_FILE, content);
            }catch(Exception e)
            {
                Debug.WriteLine("ERROR: " + e.ToString());
            }
        }

    }

Solution

  • I tried different solution but none of them worked, while it had nothing to do with calling await FilesManager.Init(); nor its implementation or anything else, I just switched to WinUI 3 Unpackaged App, its better than UWP as I know, good thing didn't find any real problem doing async stuff and reading/writing data. I only found some minor issues related to startup time of the app (which I think will be fixed in later releases of WinUI), anyway I recommend switching to it (it contains the same features of UWP and more, also it runs on dotnet core so the app could be made independent from the installation of dotnet runtime)