通过注册表获取应用程序的路径

来源:互联网 发布:java思想 编辑:程序博客网 时间:2024/06/03 23:49

孙广东  2016.7.17

http://blog.csdn.net/u010019717

      应用程序的路径虽然可以硬编码,例如,路径 ="e:\\Program Files\\Unity\\Editor\\Unity.exe",但是这不是最佳的方式,因为用户不可能将Unity安装到默认目录。  

     

          Unity内部:EditorApplication.applicationPath     《=》E:/Program Files/Unity5/Editor/Unity.exe

(任意的程序都可以啦~)

这里说的是在Unity编辑器外,  不是在Unity编辑器中!

若要提取Unity 安装文件夹,其在 windows 平台上可以使用注册表,如下所示︰


正常的应用应该是在    HKEY_LOCAL_MACHINE\SOFTWARE 下, 但是找了一下,没有找到,    然后在   HKEY_CLASSES_ROOT  下 找到

           e:\Program Files\Unity\Editor\Unity.exe

         但是Unity跟其他的应用不一样,  可以安装多个版本,  上图的路径只是最近安装的Unity的版本。

 

Python的    代码实现:

from winreg import * def GetUnityRootPath():    aReg = ConnectRegistry(None, HKEY_CLASSES_ROOT)    aKey = OpenKey(aReg, r"Unity package file\DefaultIcon")    # aKey = OpenKey(aReg, r"Unity scene file")     # 获取 '(default)'    key 的值    value = QueryValueEx(aKey, "")    print(value[0])     # 获取'\\Editor\\Unity.exe' 的起始位置    substring = value[0]    pos = substring.find("\\Editor\\Unity.exe")    print(pos)    unityPath = substring[:pos]    if unityPath[0]=="\"":        unityPath = unityPath[1:pos]     print (unityPath) if __name__ == "__main__":    GetUnityRootPath();


 

 

C# 的代码实现:

using Microsoft.Win32;using System.IO;using System;class Program{    private static string GetUnityRootPath()    {        var regKey = @"Unity package file\DefaultIcon";        RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(regKey);         string pathName = (string)registryKey.GetValue(null);  // "(Default)"        if (string.IsNullOrEmpty(pathName))        {            return null;        }         int index = pathName.LastIndexOf(",");        if (index != -1)        {            var exepath = pathName.Substring(0, index).Replace("\"", string.Empty);            var binpath = Path.GetDirectoryName(exepath);   //            var di = new DirectoryInfo(binpath);            if (di.Parent != null)            {                return di.Parent.FullName;            }        }        return null;    }    static void Main(string[] args)    {        Console.WriteLine(GetUnityRootPath());    }}


 

 http://blog.csdn.net/u010019717


1 0
原创粉丝点击