Search code examples
uwpfile-iowindows-runtimec++-winrtfilepicker

How to reassign file to StorageFile at C++/WinRT


I wrote a code which picks a file and wipe its content and save new one.
but it crashes when assigning file to StorageFile.

Note that this is excerpted code: full code is here.

#pragma once

#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Storage.Pickers.h>
#include <winrt/Windows.UI.Xaml.h>

#include "pch.h"

using namespace std;
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Pickers;
using namespace Windows::UI::Xaml;

namespace MyFilePicker
{
  struct PickAndWrite
  {
    void Save(const hstring content) noexcept
    {
      StorageFile file = nullptr;

      picker([&file]()->fire_and_forget {
        FileSavePicker savePicker;
        file = co_await savePicker.PickSaveFileAsync(); // crashes here.
      });

      writer([content, file]()->fire_and_forget {
        if (file != nullptr) { co_await FileIO::WriteTextAsync(file, content); }
      });
    }
  };
}

note that I can't unite picker and writer, because it is related with React Native.
then how can I assign it?


Solution

  • I finally found a solution. it was from a bug of React Native for Windows.
    Don't use fire_and_forget in RNW until the bug is gone.