File UWP:读取文件时捕获错误
我已成功地使用以下代码在File UWP:读取文件时捕获错误,file,error-handling,uwp,c++-cx,File,Error Handling,Uwp,C++ Cx,我已成功地使用以下代码在UWPC++应用程序中打开和读取文件: FileOpenPicker^ openPicker = ref new FileOpenPicker(); openPicker->SuggestedStartLocation= PickerLocationId::DocumentsLibrary; openPicker->FileTypeFilter->Append(".txt"); create_task(openPicker->PickSingl
UWP
C++
应用程序中打开和读取文件:
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->SuggestedStartLocation= PickerLocationId::DocumentsLibrary;
openPicker->FileTypeFilter->Append(".txt");
create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
create_task(FileIO::ReadTextAsync(file)).then([this](Platform::String^ text) {
MessageDialog^ msg = ref new MessageDialog(text);
msg->ShowAsync();
});
}
else
{
MessageDialog^ msg = ref new MessageDialog("Operation cancelled.");
msg->ShowAsync();
}
});
但是,如果文件内容是非文本的,例如二进制文件,则应用程序会崩溃。如何实现错误处理?我尝试过使用
try…catch
但没有成功。我通过参考
try…catch
应该放在异步任务中。我把它放在外面。为此,应更改create_task()
的参数:
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->SuggestedStartLocation= PickerLocationId::DocumentsLibrary;
openPicker->FileTypeFilter->Append(".txt");
create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
{
if (file)
{
create_task(FileIO::ReadTextAsync(file)).then([this](task<String^> currentTask) {
try {
String ^text = currentTask.get();
MessageDialog^ msg = ref new MessageDialog(text);
msg->ShowAsync();
}
catch (...) {
MessageDialog^ msg = ref new MessageDialog("Exception handled.");
msg->ShowAsync();
}
});
}
else
{
MessageDialog^ msg = ref new MessageDialog("Operation cancelled.");
msg->ShowAsync();
}
});
FileOpenPicker^openPicker=ref new FileOpenPicker();
openPicker->SuggestedStartLocation=PickerLocationId::DocumentsLibrary;
openPicker->FileTypeFilter->Append(“.txt”);
创建任务(openPicker->PickSingleFileAsync())。然后([this](存储文件^file)
{
如果(文件)
{
创建_任务(FileIO::ReadTextAsync(file))。然后([this](任务当前任务){
试一试{
字符串^text=currentTask.get();
MessageDialog^msg=ref新建MessageDialog(文本);
msg->showanc();
}
捕获(…){
MessageDialog^msg=ref newmessagedialog(“异常已处理”);
msg->showanc();
}
});
}
其他的
{
MessageDialog^msg=ref新建MessageDialog(“操作已取消”);
msg->showanc();
}
});
当此代码在VisualStudio中运行时,当出现错误时,它仍然会中断并显示一些十六进制符号。只需单击Continue
或F5
即可处理异常。
错误消息