【问题标题】:How do I launch files in C#如何在 C# 中启动文件
【发布时间】:2009-08-16 06:11:23
【问题描述】:

-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();
        }
    }
}

【问题讨论】:

  • 如果您尝试仅在命令行上为它们编写任何生成的调试语句,这些图像文件会发生什么情况?
  • 您只想在 Windows 中启动文件吗?

标签: c# .net shell


【解决方案1】:

用途:

System.Diagnostics.Process.Start(filePath);

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

【讨论】:

  • 哇,你刚刚打败了我 :)
  • 你想用特定程序打开它怎么样,我想用“Windows PowerShell ISE”打开它
  • 太棒了..运行良好
  • 在 windows 10 和 .net 5 上出现此错误:“指定的可执行文件不是此 OS 平台的有效应用程序”
  • @HamidZ 与该文件关联的程序不存在或无效。
【解决方案2】:

听起来您确实在寻找更多:

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

【讨论】:

    【解决方案3】:

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

    例如:

     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);
        }
    

    注意:在我的 PC 中,图片会在 Windows 图片和传真查看器中打开,因为这是 *.jpg 文件的默认应用程序。

    【讨论】:

      【解决方案4】:

      至少对我来说,使用 DotNet 5+ / Dotnet Core System.Diagnostics.Process.Start 不起作用(在 Windows 10 或 11 上)。所以我改用了 ShellExecute API。

      使用以下代码调用

      ShellExecute("文件名");

      例如。 ShellExecute("c:\temp\test.txt");

      该方法的 C# 代码:

      using System.Runtime.InteropServices;     
      [DllImport("Shell32.dll")]
              private static extern int ShellExecuteA(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirecotry, int nShowCmd);
      
          public static int ShellExecute(string filename, string parameters = "", string workingFolder = "", string verb = "open", int windowOption = 1)
          {
              //calls Windows ShellExecute API
              //for verbs see https://docs.microsoft.com/en-us/windows/win32/shell/launch (open/edit/runas...)
              //for windowOptions see https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow (show/hide/maximize etc)
      
              IntPtr parentWindow = IntPtr.Zero;
      
              try
              {
                  int pid = ShellExecuteA(parentWindow, verb, filename, parameters, workingFolder, windowOption);
                  return pid;
              }
              catch (Exception ex)
              {
                  Console.Error.WriteLine(ex.Message);
                  return 0;
              }
              
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        相关资源
        最近更新 更多