我们有一个使用System.Diagnostics.Process.Start显式启动Microsoft Word的.NET应用程序,例如"C:\PROGRA~2\MICROS~1\Office14\WINWORD.EXE“-预先从注册表中检索该值(请参阅下面代码中的GetWordExePathFromWindowsRegistry方法)。由于我们从.NET Framework4.x迁移到了.NET Core3.1,因此在Process.Start行中抛出了一个运行时错误: Win32Exception:“目录名称无效。”(在我们的例子中,德语消息"Der Verzeichnisname ist ungültig.")我们记录了错误,当我们在文件资源管理器中打开记录的目录时,一切都是正常的;因此,就我们所看到的错误消息而言,它是不正确的。这种错误并不总是发生,但经常发生。有时,它有助于重新启动应用程序,有时还会重新启动计算机。有时候什么都没有用。一些用户比其他用户更容易收到错误。另一个网站的用户根本就没有这个问题。然而,我们不知道原因是什么。
请注意,这几年来一直是多产的代码,没有问题,自从我们从.NET框架迁移到.NET Core3.1之后,我们得到了错误报告,而这些代码没有改变。
下面是获取winword.exe路径的代码:
public static string GetWordExePathFromWindowsRegistry()
{
Regex exePathRegex = new Regex(
@".*\\winword.exe",
RegexOptions.IgnoreCase);
foreach ( string wowNodeName in new[] { "", @"Wow6432Node\" })
{
foreach (string theKeyFormat in
new[]
{
@"SOFTWARE\{0}Microsoft\Windows\CurrentVersion\App Paths\Winword.exe",
@"SOFTWARE\{0}Classes\WordDocument\protocol\StdFileEditing\server",
@"SOFTWARE\{0}Classes\Word.Document.14\protocol\StdFileEditing\server"
})
{
RegistryKey rootNode = Registry.LocalMachine;
string keyPath = string.Format(theKeyFormat, wowNodeName);
// Get default registry Value:
using RegistryKey key = rootNode.OpenSubKey(keyPath);
string fullWordPath = key?.GetValue("")?.ToString();
if (!string.IsNullOrEmpty(fullWordPath))
if (exePathRegex.IsMatch(fullWordPath))
return fullWordPath;
}
}
throw new Exception("Path to Word not found"); ;
}
然后我们用这样的东西开始Word (在我们的例子中是hidden==true,因为Word中的VSTO插件做的是真正的事情):
public void StartMsOfficeAppExe(
string msOfficeAppExePath,
string startArguments,
bool hidden)
{
ProcessStartInfo startInfo = new ProcessStartInfo(
msOfficeAppExePath,
startArguments)
{
UseShellExecute = false // without this Hidden would not be allowed
};
if (hidden)
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(startInfo);
}
发布于 2021-10-18 16:36:22
您是否尝试对字符串使用逐字字符(@)?可能是因为它没有转义反斜杠。
手动转义它们也是可行的(替换\ => \\
,它们会变黄)。
https://stackoverflow.com/questions/69619415
复制相似问题