C#:关联程序和文件
一、关联代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 关联程序和类型 /// </summary> private void RegFileExt() { try { string boardExe = @"BlackBoardTool\bin\Teacher.UCBook.BlackBord.exe"; string boardExeFullName = Path.Combine(GlobalInfos.ExePath, boardExe); if (File.Exists(boardExeFullName)) { string MyExtName = ".dbb"; string MyType = "dbb_auto_file"; string MyContent = "application/dbb"; string command = "\"" + boardExeFullName + "\"" + " \"%1\""; RegistryKey key = Registry.ClassesRoot.OpenSubKey(MyType); if (key == null) { RegistryKey MyReg = Registry.ClassesRoot.CreateSubKey(MyExtName); MyReg.SetValue("", MyType); MyReg.SetValue("Content Type", MyContent); MyReg = Registry.ClassesRoot.CreateSubKey(MyType); MyReg.SetValue("", MyType); MyReg = MyReg.CreateSubKey("Shell\\Open\\Command"); MyReg.SetValue("", command); MyReg.Close(); _logger.Info("设置文件关联操作成功!"); } else { var myReg = key.OpenSubKey("Shell\\Open\\Command",true); if (myReg!=null && (myReg.GetValue("")==null || myReg.GetValue("").ToString()!=command)) { myReg.SetValue("", command);//解决因目录变化导致 注册表失效的问题 myReg.Close(); } } } } catch (Exception ex) { _logger.ErrorFormat("设置文件关联失败!{0}",ex.Message); } }
二、注释
1、前面是路径,后面的 %1就是可变参数,代表任意用xxxx.exe来执行的程序 (可传至于exe程序)
2、string command = Environment.CommandLine.Trim();//获取进程命令行参数 含:.exe 全路径、打开文件的全路径(直接通过运行环境获取命令行)
3、static void Main(string[] args){} //args:仅含打开文件的全路径,不包含.exe 全路径 (程序运行时获取参数)
三、参考:
1、
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1.写注册表的时候,最后路径要加上参数,如: [HKEY_CLASSES_ROOT\Simu\shell\open\command] @="\"x:\\simu\\Simulink.exe\" \"%1\"" 前面是路径,后面的 %1就是参数了 2.程序的主入口加入参数,以C#为例: static void Main(string[] args) { if (args.Length > 0) { MessageBox.Show(args[0].ToString()); } } 3.在写链接的时候自定义参数,程序会把整个链接都获取到,自己在进行解析 : 比如: <a href="MyOfficeCon://hello">123123</a> 会获取到 “MyOfficeCon://hello”
2、线程开启程序时传参
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
新建板书一.dbb E:\working\Client\Build\Teacher.Build\user\16\resource\mbook_de0df31a6fd14e3390a8d65c19342801\resource\4d4db1cc.dbb _boardPath: E:\working\Client\Build\Teacher.Build\bin\Teacher.UCBook.BlackBord.exe _args: 16 -p "E:\working\Client\Build\Teacher.Build\user\16\resource\mbook_de0df31a6fd14e3390a8d65c19342801\resource\4d4db1cc.dbb" 新建板书一.dbb System.Diagnostics.Process.Start(_boardPath, _args);