You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 C#中使用Process.Start打开文本文件报错的解决方法

解决.NET 6中使用Process.Start打开文本文件的错误

问题原因

错误System.ComponentModel.Win32Exception (193)的核心原因是:在.NET 6及后续版本中,ProcessStartInfo的UseShellExecute属性默认值为false。当该属性为false时,Process.Start会尝试将目标文件当作可执行程序运行,而文本文件并非可执行文件,因此触发错误。

解决方案

要通过系统默认关联程序打开文本文件,需显式将UseShellExecute设置为true,让系统调用Shell来处理文件的默认打开逻辑。

修正后的代码片段

var p = new Persistence();
var filename = @"c:\temp\journal.txt";
p.SaveToFile(j, filename);

// 配置ProcessStartInfo,启用Shell执行逻辑
var startInfo = new ProcessStartInfo(filename)
{
    UseShellExecute = true
};
Process.Start(startInfo);

补充说明

  • UseShellExecute = true时,系统会根据文件扩展名自动匹配对应的默认应用程序,并启动该程序打开目标文件。
  • 此方式适用于所有类型的文档文件(如PDF、Excel、图片等),只要系统已配置对应的默认关联程序即可正常工作。

内容的提问来源于stack exchange,提问作者Murat Ishenbaev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:37:37