使用默认应用程序打开文件的最简单方法是:
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)
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上打开特定文件类型的默认应用程序
我将由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上查找用于打开特定文件类型的默认应用程序.