Skip to content

Instantly share code, notes, and snippets.

@gyakoo
Last active January 23, 2017 20:53
Show Gist options
  • Save gyakoo/95ba9abf99eba5d9a005467f1695caec to your computer and use it in GitHub Desktop.
Save gyakoo/95ba9abf99eba5d9a005467f1695caec to your computer and use it in GitHub Desktop.
Reading an entire file into memory in UWP in an (permission-granted) path.
// This code is WIP and does not reflect the final one, but gets a rough idea on how to use continuation
// task for exception catching when workin with Async operations
inline concurrency::task<std::vector<byte>> ReadEntireFileFromPath(const std::wstring& filename)
{
using namespace Windows::Storage;
using namespace Windows::Foundation;
using namespace Concurrency;
auto taskFileFromPath = create_task(StorageFile::GetFileFromPathAsync(Platform::StringReference(filename.c_str())));
return taskFileFromPath.then([](task<StorageFile^> tfile)
{
StorageFile^ file = nullptr;
try
{
file = tfile.get();
return FileIO::ReadBufferAsync(file);
}
catch (Platform::Exception^ e)
{
cancel_current_task();
}
}).then([](task<Streams::IBuffer^> tFileBuffer)
{
std::vector<byte> returnBuffer;
try
{
Streams::IBuffer^ fileBuffer = tFileBuffer.get();
returnBuffer.resize(fileBuffer->Length);
Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
}
catch (const task_canceled& ) { }
catch (Platform::Exception^ ) { }
return returnBuffer;
});
}
@gyakoo
Copy link
Author

gyakoo commented Jan 23, 2017

It's important to pass down the continuation tasks the task<> object to avoid the .get inside ppl and getting an unhandled exception within

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment