c#使用默认应用程序和参数打开文件

Álv*_*cía 88 c# file

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

System.Diagnostics.Process.Start(@"c:\myPDF.pdf");
Run Code Online (Sandbox Code Playgroud)

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

我知道如何创建新进程并设置参数,但是这样我需要指明应用程序的路径,我希望有一个可移植的应用程序而不必设置应用程序的路径每次我在其他计算机上使用该应用程序.我的想法是,我希望计算机已经安装了pdf阅读器,只说明打开了哪个页面.

谢谢.

Jes*_*ian 38

这应该接近了!

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

    fileopener.StartInfo.FileName = "explorer";
    fileopener.StartInfo.Arguments = "\"" + path + "\"";
    fileopener.Start();
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要 StartInfo:`Process.Start("explorer", "\"" + path + "\"");` (9认同)
  • 不要忘记将其包装在 using 块中,Process 是 IDisposable。 (4认同)
  • 这对我用默认程序打开 PDF 很有用。谢谢你! (3认同)
  • @imgen 问题是关于提供页码作为参数。这个答案涵盖了这一点吗? (2认同)

dan*_*uio 37

编辑(感谢问题评论中的surfbutler评论) 如果您希望使用默认应用程序打开文件,我的意思是不指定Acrobat或Reader,您无法在指定页面中打开该文件.

另一方面,如果您在指定Acrobat或Reader时没问题,请继续阅读:


您可以在不告知完整Acrobat路径的情况下执行此操作,如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

如果您不希望使用Reader打开pdf但是使用Acrobat,请按照以下方式打开第二行:

myProcess.StartInfo.FileName = "Acrobat.exe";
Run Code Online (Sandbox Code Playgroud)

第二次编辑:查找pdf扩展名的默认应用程序

您可以查询注册表以识别打开pdf文件的默认应用程序,然后相应地在进程的StartInfo上定义FileName. Again, thanks surfbutler for your comment :)

请按照此问题获取有关执行此操作的详细信息:查找在Windows上打开特定文件类型的默认应用程序

  • +1此外,我认为可以在注册表中查找与任何文件类型相关联的应用程序,例如".pdf",然后将该名称放在filename参数中.见http://stackoverflow.com/questions/162331/finding-the-default-application-for-opening-a-particular-file-type-on-windows?rq=1 (2认同)

Oha*_*der 7

我将由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();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 这是不可靠的.请参阅在Windows上查找用于打开特定文件类型的默认应用程序.