C # 打开带有默认应用程序和参数的文件

使用默认应用程序打开文件的最简单方法是:

System.Diagnostics.Process.Start(@"c:\myPDF.pdf");

但是,我想知道是否存在一种方法来设置默认应用程序的参数,因为我想在一个确定的页码打开一个 pdf。

我知道如何创建一个新的进程和设置参数,但这种方式我需要指出的应用程序的路径,我希望有一个便携式应用程序,而不是设置路径的应用程序,每次我使用的应用程序在其他计算机。我的想法是,我希望计算机已经安装了 pdf 阅读器,只说什么页面打开。

谢谢。

142791 次浏览

你可以试试

Process process = new Process();
process.StartInfo.FileName = "yourProgram.exe";
process.StartInfo.Arguments = ..... //your parameters
process.Start();

请在“项目属性”下添加“设置”,并以这种方式使用它们,您就拥有了干净且易于配置的设置,可以将其配置为默认设置

如何: 在设计时创建新的设置

更新: 在以下评论之后

  1. 右键 + 点击项目
  2. 添加新项
  3. 在 VisualC # 项目下-> 常规
  4. 选择设置文件

如果希望用默认应用程序打开文件,我的意思是如果不指定 Acrobat 或 Reader,就不能在指定的页面中打开文件。

另一方面,如果您可以指定 Acrobat 或 Reader,请继续阅读:


你可以不用告诉杂技演员完整的路径,像这样:

using Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();

如果你不想用 Reader 打开 pdf,而是用 Acrobat 打开,可以像下面这样修改第二行:

myProcess.StartInfo.FileName = "Acrobat.exe";

您可以查询注册表以确定打开 pdf 文件的默认应用程序,然后相应地在流程的 StartInfo 上定义 FileName。

按照这个问题的细节做: 查找在 Windows 上打开特定文件类型的默认应用程序

我把 Xsl链接的博客文章中的 VB 代码转换成了 C # ,并对它进行了一些修改:

public static bool TryGetRegisteredApplication(
string extension, out string registeredApp)
{
string extensionId = GetClassesRootKeyDefaultValue(extension);
if (extensionId == null)
{
registeredApp = null;
return false;
}


string openCommand = GetClassesRootKeyDefaultValue(
Path.Combine(new[] {extensionId, "shell", "open", "command"}));


if (openCommand == null)
{
registeredApp = null;
return false;
}


registeredApp = openCommand
.Replace("%1", string.Empty)
.Replace("\"", string.Empty)
.Trim();
return true;
}


private static string GetClassesRootKeyDefaultValue(string keyPath)
{
using (var key = Registry.ClassesRoot.OpenSubKey(keyPath))
{
if (key == null)
{
return null;
}


var defaultValue = key.GetValue(null);
if (defaultValue == null)
{
return null;
}


return defaultValue.ToString();
}
}

编辑-这是不可靠的。

应该就在附近!

public static void OpenWithDefaultProgram(string path)
{
using Process fileopener = new Process();


fileopener.StartInfo.FileName = "explorer";
fileopener.StartInfo.Arguments = "\"" + path + "\"";
fileopener.Start();
}