【问题标题】:UWP: Catch error when reading fileUWP:读取文件时捕获错误
【发布时间】:2018-06-19 22:42:27
【问题描述】:

我已经能够使用以下代码在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 失败。

【问题讨论】:

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


    【解决方案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. 错误消息。

    【讨论】:

      猜你喜欢
      • 2013-02-17
      • 2020-06-20
      • 2021-06-27
      • 1970-01-01
      • 2021-07-19
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多