How to write a file without prompt a window that asks where to store it in C++/CX?

53 Views Asked by At

Normally, when we would like to store a file, we'd open a FileSavePicker like:

auto savePicker = ref new FileSavePicker();
savePicker->SuggestedStartLocation = PickerLocationId::PucturesLibrary;
savePicker->FileTypeChoices->Insert("Gif", ref new Vector<String^>({".gif"}));
savePicker->SuggestedFileName = "File1";
create_task(...); // Save file async here.

But what I want to do is that it saves the file at the local folder automatically without asking where to store it, what the name of the file is, and so on. And in an async way by the way, like:

inkCanvas->InkPresenter->StrokeContainer->SaveAsync(stream);

What should I do to create a file and then read it as a stream?

1

There are 1 best solutions below

0
Roy Li - MSFT On

If you want to save a file without having a window dialog, then the FileSavePicker is not suitable for you. If I understand you correctly, what you really want to do is to create a file directly so that you could save data into that file.

The simplest way is that you need to get a StorageFolder object that represents the target folder. Then you could call StorageFolder.CreateFileAsync. This API will create a file and it won't prompt a dialog.

If the target folder is a known folder like Vidoe, Document, etc, then you just need to call KnownFolders Class.

Like this:

StorageFile file = await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("ink.gif", CreationCollisionOption.ReplaceExisting);

If the target folder is a place where the UWP app doesn't have permission to access by default, then you might need to take a look at broadFileSystemAccess capability. This restricted capability enables your app to get the same access to the file system as the user who is currently running the app without any additional file-picker style prompts during runtime. This capability only works for APIs in Windows.Storage namespace.

Then you could use it like this:

  var folder = await StorageFolder.GetFolderFromPathAsync(folderPath);
  var file = await folder.CreateFileAsync("ink.gif", CreationCollisionOption.ReplaceExisting);

For more information about file system permission in UWP, please refer to: File permission