UWP:读取文件时出现捕获错误

时间:2018-06-18 09:16:47

标签: file error-handling uwp c++-cx

我已成功使用以下代码在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失败了。

1 个答案:

答案 0 :(得分:1)

我设法通过参考来解决问题

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();
    }
});

在Visual Studio中运行此代码时,发生错误时,它仍会中断,并显示一些十六进制符号。只需单击ContinueF5即可获得Exception handled.错误消息。