gpt4 book ai didi

file - UWP : Catch error when reading file

转载 作者:行者123 更新时间:2023-12-03 08:23:25 24 4
gpt4 key购买 nike

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

最佳答案

我设法通过解决问题

  • https://social.msdn.microsoft.com/Forums/en-US/5b84396b-f071-4c29-ab11-78757d0206f1/uwp-try-catch-block-doesnt-work-in-my-uwp?forum=wpdevelop
  • Exception handling, WinRT C++ concurrency async tasks
  • 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.错误消息。

    关于file - UWP : Catch error when reading file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50906157/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com