异步文件选择方法需等PickAsync完成再做空检查,首次运行偶现result为null
问题分析与解决方案
你的代码里await关键字已经确保FilePicker.PickAsync执行完成后才会执行后续代码,不存在空检查提前执行的情况。首次选择文件时result为null,大概率是以下原因:
- 用户取消了文件选择操作(
PickAsync在用户取消时会返回null) - 直接访问
result.FileName前未检查result本身是否为null,导致抛出NullReferenceException,代码进入catch块但未做处理,看起来像是Label没更新
修改后的代码
private async void PickFileButton_Clicked(object sender, EventArgs e) { try { Console.WriteLine("checkpoint1"); FileResult result = await FilePicker.PickAsync(new PickOptions { FileTypes = new FilePickerFileType( new Dictionary<DevicePlatform, IEnumerable<string>> { { DevicePlatform.iOS, new[] { "public.item" } }, { DevicePlatform.Android, new[] { "*/*" } }, { DevicePlatform.WinUI, new[] { "*/*" } }, { DevicePlatform.MacCatalyst, new[] { "public.item" } } }) }); Console.WriteLine("checkpoint2"); // 先检查result是否不为null,再检查FileName if (result != null && !string.IsNullOrEmpty(result.FileName)) { filePath = result.FullPath; FilePathLabel.Text = filePath; Console.WriteLine(FilePathLabel.Text); } else { // 可选:处理用户取消选择或文件信息异常的情况 Console.WriteLine("未选择有效文件"); } } catch (Exception ex) { Console.WriteLine($"文件选择失败: {ex.Message}"); // 可选:给用户显示错误提示 // FilePathLabel.Text = "文件选择出错,请重试"; } }
关键修改点
- 增加
result != null的前置检查:避免result为null时访问FileName导致空引用异常 - 使用
string.IsNullOrEmpty替代单纯的!= null:同时处理FileName为空字符串的情况 - 增加else分支:明确处理未选择有效文件的场景,方便排查问题
另外,代码中PickAsync后面的双重分号是笔误,已移除,不影响功能但建议规范写法。
内容的提问来源于stack exchange,提问作者an22
相关产品推荐
相关产品推荐

