获取应用程序的路径可以说是一个不大不小的需求,那么有什么好的方法来实现呢,正是下面要和大家介绍的通过注册表获取应用程序的路径,想知道的可以看看。
应用程序的路径虽然可以硬编码,例如,路径 ="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")
-
-
-
-
-
-
-
- value = QueryValueEx(aKey, "")
-
- print(value[0])
-
-
-
-
-
- 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);
-
- 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());
-
- }
-
- }
