C#中使用Process.Start打开.url快捷方式失败,求解决方案
问题描述
尝试使用Process.Start()通过.url链接启动应用,但官方文档说明:
若启动的可执行文件地址为URL,进程不会启动并返回null。
目前无法通过其他方式启动该应用,请问是否存在可行的替代方案?
以下是使用的代码:
Process proc = new Process(); Trace.WriteLine(MainDataModel.Default.FilePaths.ExecutableDirectory + "\\Minecraft Preview_Editor.url"); proc.StartInfo.FileName = MainDataModel.Default.FilePaths.ExecutableDirectory + "\\Minecraft Preview_Editor.url"; proc.Start();
对应的报错信息:
BedrockLauncher.Exceptions.AppLaunchFailedException: An error occurred trying to start process 'C:\\Users\<me>\\Documents\\GitHub\\BedrockLauncher\\BedrockLauncher\\bin\\Debug\\net6.0-windows10.0.17763.0\\Minecraft Preview_Editor.url' with working directory 'C:\\Users\<me>\\Documents\\GitHub\\BedrockLauncher\\BedrockLauncher\\bin\\Debug\\net6.0-windows10.0.17763.0'. The specified executable is not a valid application for this OS platform.
解决方案
.url是Windows系统的快捷方式文件(本质为INI格式文本文件),并非可执行程序,直接通过Process.Start()指定其为FileName会触发平台不兼容报错。以下是三种可行的替代方案:
方案1:启用ShellExecute打开.url文件
通过启用UseShellExecute,让系统调用默认Shell处理.url文件,效果等同于手动双击该文件:
ProcessStartInfo startInfo = new ProcessStartInfo { FileName = Path.Combine(MainDataModel.Default.FilePaths.ExecutableDirectory, "Minecraft Preview_Editor.url"), UseShellExecute = true }; Process.Start(startInfo);
方案2:解析.url文件提取目标路径后启动
.url文件包含URL=开头的行,对应快捷方式指向的目标地址。读取并解析该行内容,直接启动目标路径:
string urlFilePath = Path.Combine(MainDataModel.Default.FilePaths.ExecutableDirectory, "Minecraft Preview_Editor.url"); string targetPath = File.ReadAllLines(urlFilePath) .First(line => line.StartsWith("URL=")) .Substring(4); Process.Start(new ProcessStartInfo(targetPath) { UseShellExecute = true });
注:若目标为本地应用路径可直接启动;若为网页URL,UseShellExecute=true会调用默认浏览器打开。
方案3:通过cmd命令启动
借助cmd的start命令触发系统Shell处理.url文件:
string urlFilePath = Path.Combine(MainDataModel.Default.FilePaths.ExecutableDirectory, "Minecraft Preview_Editor.url"); Process.Start("cmd.exe", $"/c start \"\" \"{urlFilePath}\"");
内容的提问来源于stack exchange,提问作者MetalManeMc
相关产品推荐
相关产品推荐

