Mur*_*aev 1 .net c# design-patterns
我正在使用 .NET 6.0 在 C# 中开发控制台应用程序。我有一个用于存储条目的 Journal 类和一个用于将日记条目保存到文件的 Persistence 类。当我尝试使用打开保存的文本文件时遇到错误Process.Start。错误信息如下:
Unhandled exception. System.ComponentModel.Win32Exception (193): An error occurred trying to start process 'c:\temp\journal.txt' with working directory 'C:\Mentorship\Design Patterns\bin\Debug\net6.0'. The specified executable is not a valid application for this OS platform.
Run Code Online (Sandbox Code Playgroud)
我的代码的相关部分:
Unhandled exception. System.ComponentModel.Win32Exception (193): An error occurred trying to start process 'c:\temp\journal.txt' with working directory 'C:\Mentorship\Design Patterns\bin\Debug\net6.0'. The specified executable is not a valid application for this OS platform.
Run Code Online (Sandbox Code Playgroud)
我期望此代码使用默认的关联程序打开保存的文本文件。但是,我收到了上面提到的错误。如何解决此问题并Process.Start在 .NET 6.0 中成功打开文本文件?
好吧,异常消息以纯文本形式告诉您:
尝试使用工作目录“C:\Mentorship\Design Patterns\bin\Debug\net6.0”启动进程“c:\temp\journal.txt”时发生错误。指定的可执行文件不是此操作系统平台的有效应用程序。
因此,您的程序尝试像程序一样执行journal.txt 文件。这与代码中的此代码行相关:Process.Start(filename)。
请注意,这并不是您想象的那样编写文本文件的问题。问题主要在于尝试像程序一样执行写入的文本文件。
如果您希望在文本编辑器中打开文本文件,那么将Process.Start(string)无济于事,因为它不适用于非可执行文件。(过去确实如此,但Process.Start(string)的行为 已随 .NET Core 2.1 更改。)要告诉操作系统使用关联的应用程序(通常是文本编辑器)打开文本文件,您可以使用该Process.Start(ProcessStartInfo)方法连同显式设置ProcessStartInfo.UseShellExecute为true:
var psi = new ProcessStartInfo(txtFilePath)
{
UseShellExecute = true
};
Process.Start(psi);
Run Code Online (Sandbox Code Playgroud)
Process.Start(string)按照典型的 Microsoft 方式,自 2018 年随 .NET Core 2.1 引入以来,.NET 团队未能更新官方 API 文档来反映更改后的行为。虽然已经提交了有关过时文档的错误报告 ( https: //github.com/dotnet/dotnet-api-docs/issues/8727),文档问题至今仍然存在......:-(
| 归档时间: |
|
| 查看次数: |
1172 次 |
| 最近记录: |