如何在C#中启动文件

时间:2009-08-16 06:11:24

标签: c# .net shell

-Edit-我觉得自己像个白痴。我有一种感觉,下面的答案会起作用,但没有看到任何谷歌的结果类似于下面的答案。所以,当我看到这个复杂的代码时,我认为它必须是这样的。

我搜索并找到了这个Windows: List and Launch applications associated with an extension然而它没有回答我的问题。通过下面的调整,我提出了以下内容。但它会卡在图像文件上。 Txt文件运行正常

我会尽快更新此代码,以便考虑带有空格的应用路径,但我不明白为什么图片文件不会启动。

static void launchFile(string fn)
{
    //majority was taken from
    //https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension
    const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}";
    const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command";

    string ext = Path.GetExtension(fn);

    var extPath = string.Format(extPathTemplate, ext);

    var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;
    if (!string.IsNullOrEmpty(docName))
    {
        // 2. Find out which command is associated with our extension
        var associatedCmdPath = string.Format(cmdPathTemplate, docName);
        var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;

        if (!string.IsNullOrEmpty(associatedCmd))
        {
            //Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext);
            var p = new Process();
            p.StartInfo.FileName = associatedCmd.Split(' ')[0];
            string s2 = associatedCmd.Substring(p.StartInfo.FileName.Length + 1);
            s2 = s2.Replace("%1", string.Format("\"{0}\"", fn));
            p.StartInfo.Arguments = s2;//string.Format("\"{0}\"", fn);
            p.Start();
        }
    }
}

3 个答案:

答案 0 :(得分:89)

使用:

System.Diagnostics.Process.Start(filePath);

它将使用将打开的默认程序,就像您单击它一样。不可否认,它不允许您选择将运行的程序...但假设您想模仿用户双击该文件时将使用的行为,这应该可以正常工作。

答案 1 :(得分:11)

听起来你真的看起来更喜欢这个:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "<whatever>";
proc.Start();

答案 2 :(得分:3)

假设您只想启动已经有一些关联应用程序的文件(例如:* .txt与记事本相关联), 使用System.Diagnostics.Process。

e.g。 :

 using System.Diagnostics;
    Process p = new Process();
    ProcessStartInfo pi = new ProcessStartInfo();
    pi.UseShellExecute = true;
    pi.FileName = @"MY_FILE_WITH_FULL_PATH.jpg";
    p.StartInfo = pi;

    try
    {
        p.Start();
    }
    catch (Exception Ex)
    {
        //MessageBox.Show(Ex.Message);
    }

注意:在我的电脑中,图片在Windows Picture&amp; amp;传真查看器,因为这是* .jpg文件的默认应用程序。

相关问题