.NET 6 WPF中Process.Start无法打开文件问题求助
.NET 6 WPF 文件打开异常修复方案
错误根源分析
从异常信息和代码来看,问题出在三个方面:
- 路径混合了正斜杠
/和反斜杠\,Windows系统无法正确识别这种非标准格式的路径 - .NET 6+ 中
Process.Start(string)的默认行为在部分环境下未启用ShellExecute,而打开PDF/PNG这类非可执行文件必须依赖系统关联程序,需显式启用该属性 - 缺少空值校验,若未找到对应文件,调用
Process.Start会触发空引用异常
修复步骤
1. 统一路径格式
使用Path.GetFullPath()方法将搜索到的文件路径转换为Windows标准格式,自动处理混合斜杠问题。
2. 正确配置Process启动参数
改用ProcessStartInfo类,显式设置UseShellExecute = true,确保系统能调用默认关联程序打开目标文件。
3. 添加空值校验
在打开文件前检查目标路径是否为空,提前拦截异常并给出提示。
4. 优化文件搜索逻辑(可选)
用Path.GetExtension()替代字符串Contains判断文件类型,避免误判文件名中包含.pdf/.png的文件;同时重置数组避免旧数据干扰,只保留第一个匹配的目标文件。
修改后的代码示例
using System; using System.IO; using System.Windows; namespace IEFileViewe { public partial class MainWindow : Window { string KNR; string[] files = new string[3]; string[] allfiles; string directory = "Y:/Lehmann/Files"; public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { KNR = txt_Search.Text; if (string.IsNullOrEmpty(KNR)) { txtBlock.Text = "请输入搜索编号"; return; } allfiles = Directory.GetFiles(directory); // 重置数组清除旧数据 files[0] = null; files[1] = null; foreach (string file in allfiles) { var fileName = Path.GetFileName(file); if (fileName.Contains(KNR)) { var extension = Path.GetExtension(file).ToLower(); // 只保留第一个匹配的PDF/PNG if (extension == ".pdf" && files[0] == null) files[0] = Path.GetFullPath(file); else if (extension == ".png" && files[1] == null) files[1] = Path.GetFullPath(file); } } // 更新显示内容 txtBlock.Text = string.Empty; if (!string.IsNullOrEmpty(files[0])) txtBlock.Text += $"PDF文件: {files[0]}\n"; if (!string.IsNullOrEmpty(files[1])) txtBlock.Text += $"PNG文件: {files[1]}\n"; if (string.IsNullOrEmpty(txtBlock.Text)) txtBlock.Text = "未找到匹配的文件"; } private void btnPDF_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(files[0])) { MessageBox.Show("未找到可打开的PDF文件"); return; } var startInfo = new System.Diagnostics.ProcessStartInfo(files[0]) { UseShellExecute = true }; System.Diagnostics.Process.Start(startInfo); } private void btnPNG_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(files[1])) { MessageBox.Show("未找到可打开的PNG文件"); return; } var startInfo = new System.Diagnostics.ProcessStartInfo(files[1]) { UseShellExecute = true }; System.Diagnostics.Process.Start(startInfo); } } }
内容的提问来源于stack exchange,提问作者user20202784
相关产品推荐
相关产品推荐

