C#基礎-如何找到devenv的路徑位置


一、前言

       今年開始安裝了VS2017,有時候需要使用到腳本編譯,奈何MS在VS2017上的腳本編譯上不再支持VS2015那種 "%VS140COMNTOOLS%vsvars32.bat",我真是服了。那么沒辦法,我使用devenv總可以吧,於是我就寫了一段程序用於獲取最新版本VS的devenv。網上招數也挺多的,什么vswhere,什么判斷絕對路徑,等等。我覺得我還是從注冊表作為突破口比較好。

 

二、代碼

var hasVS = false;
var registryPath = @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7";
var localMachineRegistry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
var vsPaths = ReadRegistryInfo(localMachineRegistry, registryPath);
var highestVSdevenvPath = string.Empty;
if (vsPaths != null && vsPaths.Any())
{
    var tempVersion = 0;
    foreach (KeyValuePair<string, string> kvp in vsPaths)
    {
          var devenvExePath = Path.Combine(kvp.Value, @"Common7\IDE\devenv.exe");
          if (File.Exists(devenvExePath))
          {
              var currentVersion = Convert.ToInt32(kvp.Key.Split('.')[0]);
              if (currentVersion > tempVersion)
              {
                   tempVersion = currentVersion;
                   highestVSdevenvPath = devenvExePath;
              }
           }
    }

    if (!string.IsNullOrEmpty(highestVSdevenvPath))
    {
          hasVS = true;
    }
}


//Read Registry Info
public Dictionary<string, string> ReadRegistryInfo(RegistryKey registryKey, string registryInfoPath)
{
    if (registryKey == null || string.IsNullOrEmpty(registryInfoPath)) return null;
    try
    {
         RegistryKey rsg = registryKey.OpenSubKey(registryInfoPath, false);
         if (rsg != null)
         {
             var keyNameArray = rsg?.GetValueNames();
             var result = new Dictionary<string, string>();
             foreach (var name in keyNameArray)
             {
                  string keyValue = (string)rsg.GetValue(name);
                  result.Add(name,keyValue);
             }
             rsg.Close();
             return result;
         }
         return null;
   }
   catch
   {
         return null;
    }
}

 

找到了devenv.exe,那么剩下的事情就都好辦了,搞一個C#編譯混淆打包小工具妥妥的。

 

三、結尾

       這篇可能是在老東家時期寫的最后一篇博客了,下個月就去設計院擔任數字中心第一位BIM/Revit軟件工程師。兩年來在公司學到很多很多,來自Autodesk的老師傅們手把手的把我培養成一名全棧工程師,真的感謝他們!我這個行業圈子很小,來日方長,說不定哪天又相聚了。祝福我的同事們和領導們,謝謝他們!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM