Utilities.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Management.Automation;
  9. using System.Net;
  10. using System.Net.NetworkInformation;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Security.Principal;
  14. using System.ServiceProcess;
  15. using System.Threading.Tasks;
  16. using System.Windows.Forms;
  17. namespace Optimizer
  18. {
  19. internal static class Utilities
  20. {
  21. internal static readonly string LocalMachineRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  22. internal static readonly string LocalMachineRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  23. internal static readonly string LocalMachineRunWoW = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run";
  24. internal static readonly string LocalMachineRunOnceWow = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  25. internal static readonly string CurrentUserRun = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
  26. internal static readonly string CurrentUserRunOnce = "Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
  27. internal static readonly string LocalMachineStartupFolder = CleanHelper.ProgramData + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  28. internal static readonly string CurrentUserStartupFolder = CleanHelper.ProfileAppDataRoaming + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
  29. // DEPRECATED
  30. //internal readonly static string DefaultEdgeDownloadFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
  31. internal static WindowsVersion CurrentWindowsVersion = WindowsVersion.Unsupported;
  32. internal static Ping pinger = new Ping();
  33. static IPAddress addressToPing;
  34. static string productName = string.Empty;
  35. static string buildNumber = string.Empty;
  36. internal delegate void SetControlPropertyThreadSafeDelegate(Control control, string propertyName, object propertyValue);
  37. internal static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
  38. {
  39. if (control.InvokeRequired)
  40. {
  41. control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
  42. }
  43. else
  44. {
  45. control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
  46. }
  47. }
  48. internal static IEnumerable<Control> GetSelfAndChildrenRecursive(Control parent)
  49. {
  50. List<Control> controls = new List<Control>();
  51. foreach (Control child in parent.Controls)
  52. {
  53. controls.AddRange(GetSelfAndChildrenRecursive(child));
  54. }
  55. controls.Add(parent);
  56. return controls;
  57. }
  58. internal static Color ToGrayScale(this Color originalColor)
  59. {
  60. if (originalColor.Equals(Color.Transparent))
  61. return originalColor;
  62. int grayScale = (int)((originalColor.R * .299) + (originalColor.G * .587) + (originalColor.B * .114));
  63. return Color.FromArgb(grayScale, grayScale, grayScale);
  64. }
  65. internal static string GetWindows10Build()
  66. {
  67. return (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ReleaseId", "");
  68. }
  69. internal static string GetOS()
  70. {
  71. productName = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "");
  72. if (productName.Contains("Windows 7"))
  73. {
  74. CurrentWindowsVersion = WindowsVersion.Windows7;
  75. }
  76. if ((productName.Contains("Windows 8")) || (productName.Contains("Windows 8.1")))
  77. {
  78. CurrentWindowsVersion = WindowsVersion.Windows8;
  79. }
  80. if (productName.Contains("Windows 10"))
  81. {
  82. buildNumber = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuild", "");
  83. if (Convert.ToInt32(buildNumber) >= 22000)
  84. {
  85. productName = productName.Replace("Windows 10", "Windows 11");
  86. CurrentWindowsVersion = WindowsVersion.Windows11;
  87. }
  88. else
  89. {
  90. CurrentWindowsVersion = WindowsVersion.Windows10;
  91. }
  92. }
  93. if (Program.UNSAFE_MODE)
  94. {
  95. if (productName.Contains("Windows Server 2008"))
  96. {
  97. CurrentWindowsVersion = WindowsVersion.Windows7;
  98. }
  99. if (productName.Contains("Windows Server 2012"))
  100. {
  101. CurrentWindowsVersion = WindowsVersion.Windows8;
  102. }
  103. if (productName.Contains("Windows Server 2016") || productName.Contains("Windows Server 2019") || productName.Contains("Windows Server 2022"))
  104. {
  105. CurrentWindowsVersion = WindowsVersion.Windows10;
  106. }
  107. }
  108. return productName;
  109. }
  110. internal static string GetBitness()
  111. {
  112. string bitness = string.Empty;
  113. if (Environment.Is64BitOperatingSystem)
  114. {
  115. bitness = "You are working with 64-bit";
  116. }
  117. else
  118. {
  119. bitness = "You are working with 32-bit";
  120. }
  121. return bitness;
  122. }
  123. internal static bool IsAdmin()
  124. {
  125. return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  126. }
  127. internal static bool IsCompatible()
  128. {
  129. bool legit;
  130. string os = GetOS();
  131. if ((os.Contains("XP")) || (os.Contains("Vista")) || os.Contains("Server 2003"))
  132. {
  133. legit = false;
  134. }
  135. else
  136. {
  137. legit = true;
  138. }
  139. return legit;
  140. }
  141. // DEPRECATED
  142. //internal static string GetEdgeDownloadFolder()
  143. //{
  144. // string current = string.Empty;
  145. // try
  146. // {
  147. // current = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", DefaultEdgeDownloadFolder).ToString();
  148. // }
  149. // catch (Exception ex)
  150. // {
  151. // current = DefaultEdgeDownloadFolder;
  152. // ErrorLogger.LogError("Utilities.GetEdgeDownloadFolder", ex.Message, ex.StackTrace);
  153. // }
  154. // return current;
  155. //}
  156. // DEPRECATED
  157. //internal static void SetEdgeDownloadFolder(string path)
  158. //{
  159. // Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Edge", "DownloadDirectory", path, RegistryValueKind.String);
  160. //}
  161. internal static void RunBatchFile(string batchFile)
  162. {
  163. try
  164. {
  165. using (Process p = new Process())
  166. {
  167. p.StartInfo.CreateNoWindow = true;
  168. p.StartInfo.FileName = batchFile;
  169. p.StartInfo.UseShellExecute = false;
  170. p.Start();
  171. p.WaitForExit();
  172. p.Close();
  173. }
  174. }
  175. catch (Exception ex)
  176. {
  177. ErrorLogger.LogError("Utilities.RunBatchFile", ex.Message, ex.StackTrace);
  178. }
  179. }
  180. internal static void ImportRegistryScript(string scriptFile)
  181. {
  182. string path = "\"" + scriptFile + "\"";
  183. Process p = new Process();
  184. try
  185. {
  186. p.StartInfo.FileName = "regedit.exe";
  187. p.StartInfo.UseShellExecute = false;
  188. p = Process.Start("regedit.exe", "/s " + path);
  189. p.WaitForExit();
  190. }
  191. catch (Exception ex)
  192. {
  193. p.Dispose();
  194. ErrorLogger.LogError("Utilities.ImportRegistryScript", ex.Message, ex.StackTrace);
  195. }
  196. finally
  197. {
  198. p.Dispose();
  199. }
  200. }
  201. internal static void Reboot()
  202. {
  203. Utilities.RunCommand("shutdown /r /t 0");
  204. }
  205. internal static void ActivateMainForm()
  206. {
  207. Program._MainForm.Activate();
  208. }
  209. internal static bool ServiceExists(string serviceName)
  210. {
  211. return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName));
  212. }
  213. internal static void StopService(string serviceName)
  214. {
  215. if (ServiceExists(serviceName))
  216. {
  217. ServiceController sc = new ServiceController(serviceName);
  218. if (sc.CanStop)
  219. {
  220. sc.Stop();
  221. }
  222. }
  223. }
  224. internal static void StartService(string serviceName)
  225. {
  226. if (ServiceExists(serviceName))
  227. {
  228. ServiceController sc = new ServiceController(serviceName);
  229. try
  230. {
  231. sc.Start();
  232. }
  233. catch (Exception ex)
  234. {
  235. ErrorLogger.LogError("Utilities.StartService", ex.Message, ex.StackTrace);
  236. }
  237. }
  238. }
  239. private static void GetRegistryStartupItemsHelper(ref List<StartupItem> list, StartupItemLocation location, StartupItemType type)
  240. {
  241. string keyPath = string.Empty;
  242. RegistryKey hive = null;
  243. if (location == StartupItemLocation.HKLM)
  244. {
  245. hive = Registry.LocalMachine;
  246. if (type == StartupItemType.Run)
  247. {
  248. keyPath = LocalMachineRun;
  249. }
  250. else if (type == StartupItemType.RunOnce)
  251. {
  252. keyPath = LocalMachineRunOnce;
  253. }
  254. }
  255. else if (location == StartupItemLocation.HKLMWoW)
  256. {
  257. hive = Registry.LocalMachine;
  258. if (type == StartupItemType.Run)
  259. {
  260. keyPath = LocalMachineRunWoW;
  261. }
  262. else if (type == StartupItemType.RunOnce)
  263. {
  264. keyPath = LocalMachineRunOnceWow;
  265. }
  266. }
  267. else if (location == StartupItemLocation.HKCU)
  268. {
  269. hive = Registry.CurrentUser;
  270. if (type == StartupItemType.Run)
  271. {
  272. keyPath = CurrentUserRun;
  273. }
  274. else if (type == StartupItemType.RunOnce)
  275. {
  276. keyPath = CurrentUserRunOnce;
  277. }
  278. }
  279. if (hive != null)
  280. {
  281. try
  282. {
  283. RegistryKey key = hive.OpenSubKey(keyPath, true);
  284. if (key != null)
  285. {
  286. string[] valueNames = key.GetValueNames();
  287. foreach (string x in valueNames)
  288. {
  289. try
  290. {
  291. RegistryStartupItem item = new RegistryStartupItem();
  292. item.Name = x;
  293. item.FileLocation = key.GetValue(x).ToString();
  294. item.Key = key;
  295. item.RegistryLocation = location;
  296. item.StartupType = type;
  297. list.Add(item);
  298. }
  299. catch (Exception ex)
  300. {
  301. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  302. }
  303. }
  304. }
  305. }
  306. catch (Exception ex)
  307. {
  308. ErrorLogger.LogError("Utilities.GetRegistryStartupItemsHelper", ex.Message, ex.StackTrace);
  309. }
  310. }
  311. }
  312. private static void GetFolderStartupItemsHelper(ref List<StartupItem> list, string[] files, string[] shortcuts)
  313. {
  314. foreach (string file in files)
  315. {
  316. try
  317. {
  318. FolderStartupItem item = new FolderStartupItem();
  319. item.Name = Path.GetFileNameWithoutExtension(file);
  320. item.FileLocation = file;
  321. item.Shortcut = file;
  322. item.RegistryLocation = StartupItemLocation.Folder;
  323. list.Add(item);
  324. }
  325. catch (Exception ex)
  326. {
  327. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  328. }
  329. }
  330. foreach (string shortcut in shortcuts)
  331. {
  332. try
  333. {
  334. FolderStartupItem item = new FolderStartupItem();
  335. item.Name = Path.GetFileNameWithoutExtension(shortcut);
  336. item.FileLocation = GetShortcutTargetFile(shortcut);
  337. item.Shortcut = shortcut;
  338. item.RegistryLocation = StartupItemLocation.Folder;
  339. list.Add(item);
  340. }
  341. catch (Exception ex)
  342. {
  343. ErrorLogger.LogError("Utilities.GetFolderStartupItemsHelper", ex.Message, ex.StackTrace);
  344. }
  345. }
  346. }
  347. internal static List<StartupItem> GetStartupItems()
  348. {
  349. List<StartupItem> startupItems = new List<StartupItem>();
  350. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.Run);
  351. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLM, StartupItemType.RunOnce);
  352. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.Run);
  353. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKCU, StartupItemType.RunOnce);
  354. if (Environment.Is64BitOperatingSystem)
  355. {
  356. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.Run);
  357. GetRegistryStartupItemsHelper(ref startupItems, StartupItemLocation.HKLMWoW, StartupItemType.RunOnce);
  358. }
  359. if (Directory.Exists(CurrentUserStartupFolder))
  360. {
  361. string[] currentUserFiles = Directory.EnumerateFiles(CurrentUserStartupFolder, "*.*", SearchOption.AllDirectories)
  362. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  363. string[] currentUserShortcuts = Directory.GetFiles(CurrentUserStartupFolder, "*.lnk", SearchOption.AllDirectories);
  364. GetFolderStartupItemsHelper(ref startupItems, currentUserFiles, currentUserShortcuts);
  365. }
  366. if (Directory.Exists(LocalMachineStartupFolder))
  367. {
  368. string[] localMachineFiles = Directory.EnumerateFiles(LocalMachineStartupFolder, "*.*", SearchOption.AllDirectories)
  369. .Where(s => s.EndsWith(".exe") || s.EndsWith(".bat")).ToArray();
  370. string[] localMachineShortcuts = Directory.GetFiles(LocalMachineStartupFolder, "*.lnk", SearchOption.AllDirectories);
  371. GetFolderStartupItemsHelper(ref startupItems, localMachineFiles, localMachineShortcuts);
  372. }
  373. return startupItems;
  374. }
  375. internal static void EnableFirewall()
  376. {
  377. RunCommand("netsh advfirewall set currentprofile state on");
  378. }
  379. internal static void EnableCommandPrompt()
  380. {
  381. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Policies\\Microsoft\\Windows\\System"))
  382. {
  383. key.SetValue("DisableCMD", 0, RegistryValueKind.DWord);
  384. }
  385. }
  386. internal static void EnableControlPanel()
  387. {
  388. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  389. {
  390. key.SetValue("NoControlPanel", 0, RegistryValueKind.DWord);
  391. }
  392. }
  393. internal static void EnableFolderOptions()
  394. {
  395. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  396. {
  397. key.SetValue("NoFolderOptions", 0, RegistryValueKind.DWord);
  398. }
  399. }
  400. internal static void EnableRunDialog()
  401. {
  402. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  403. {
  404. key.SetValue("NoRun", 0, RegistryValueKind.DWord);
  405. }
  406. }
  407. internal static void EnableContextMenu()
  408. {
  409. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"))
  410. {
  411. key.SetValue("NoViewContextMenu", 0, RegistryValueKind.DWord);
  412. }
  413. }
  414. internal static void EnableTaskManager()
  415. {
  416. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  417. {
  418. key.SetValue("DisableTaskMgr", 0, RegistryValueKind.DWord);
  419. }
  420. }
  421. internal static void EnableRegistryEditor()
  422. {
  423. using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"))
  424. {
  425. key.SetValue("DisableRegistryTools", 0, RegistryValueKind.DWord);
  426. }
  427. }
  428. internal static void RunCommand(string command)
  429. {
  430. using (Process p = new Process())
  431. {
  432. p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  433. p.StartInfo.FileName = "cmd.exe";
  434. p.StartInfo.Arguments = "/C " + command;
  435. try
  436. {
  437. p.Start();
  438. p.WaitForExit();
  439. p.Close();
  440. }
  441. catch (Exception ex)
  442. {
  443. ErrorLogger.LogError("Utilities.RunCommand", ex.Message, ex.StackTrace);
  444. }
  445. }
  446. }
  447. internal static void FindFile(string fileName)
  448. {
  449. if (File.Exists(fileName))
  450. {
  451. Process.Start("explorer.exe", "/select, " + fileName);
  452. }
  453. }
  454. internal static string GetShortcutTargetFile(string shortcutFilename)
  455. {
  456. string pathOnly = Path.GetDirectoryName(shortcutFilename);
  457. string filenameOnly = Path.GetFileName(shortcutFilename);
  458. Shell32.Shell shell = new Shell32.Shell();
  459. Shell32.Folder folder = shell.NameSpace(pathOnly);
  460. Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
  461. if (folderItem != null)
  462. {
  463. Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
  464. return link.Path;
  465. }
  466. return string.Empty;
  467. }
  468. internal static void RestartExplorer()
  469. {
  470. const string explorer = "explorer.exe";
  471. string explorerPath = string.Format("{0}\\{1}", Environment.GetEnvironmentVariable("WINDIR"), explorer);
  472. foreach (Process process in Process.GetProcesses())
  473. {
  474. try
  475. {
  476. if (string.Compare(process.MainModule.FileName, explorerPath, StringComparison.OrdinalIgnoreCase) == 0)
  477. {
  478. process.Kill();
  479. }
  480. }
  481. catch (Exception ex)
  482. {
  483. ErrorLogger.LogError("Utilities.RestartExplorer", ex.Message, ex.StackTrace);
  484. }
  485. }
  486. Process.Start(explorer);
  487. }
  488. internal static void FindKeyInRegistry(string key)
  489. {
  490. try
  491. {
  492. Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", key);
  493. Process.Start("regedit");
  494. }
  495. catch (Exception ex)
  496. {
  497. ErrorLogger.LogError("Utilities.FindKeyInRegistry", ex.Message, ex.StackTrace);
  498. }
  499. }
  500. internal static List<string> GetModernApps(bool showAll)
  501. {
  502. List<string> modernApps = new List<string>();
  503. using (PowerShell script = PowerShell.Create())
  504. {
  505. if (showAll)
  506. {
  507. script.AddScript("Get-AppxPackage -AllUsers | Select -Unique Name | Out-String -Stream");
  508. }
  509. else
  510. {
  511. script.AddScript(@"Get-AppxPackage -AllUsers | Where {$_.NonRemovable -like ""False""} | Select -Unique Name | Out-String -Stream");
  512. }
  513. string tmp = string.Empty;
  514. foreach (PSObject x in script.Invoke())
  515. {
  516. tmp = x.ToString().Trim();
  517. if (!string.IsNullOrEmpty(tmp) && !tmp.Contains("---") && !tmp.Equals("Name"))
  518. {
  519. modernApps.Add(tmp);
  520. }
  521. }
  522. }
  523. return modernApps;
  524. }
  525. internal static bool UninstallModernApp(string appName)
  526. {
  527. using (PowerShell script = PowerShell.Create())
  528. {
  529. script.AddScript(string.Format("Get-AppxPackage -AllUsers *{0}* | Remove-AppxPackage", appName));
  530. script.Invoke();
  531. return script.Streams.Error.Count > 0;
  532. // not working on Windows 7 anymore
  533. //return script.HadErrors;
  534. }
  535. }
  536. internal static void ResetConfiguration(bool withoutRestart = false)
  537. {
  538. try
  539. {
  540. Directory.Delete(Required.CoreFolder, true);
  541. }
  542. catch (Exception ex)
  543. {
  544. ErrorLogger.LogError("Utilities.ResetConfiguration", ex.Message, ex.StackTrace);
  545. }
  546. finally
  547. {
  548. if (withoutRestart == false)
  549. {
  550. // BYPASS SINGLE-INSTANCE MECHANISM
  551. if (Program.MUTEX != null)
  552. {
  553. Program.MUTEX.ReleaseMutex();
  554. Program.MUTEX.Dispose();
  555. Program.MUTEX = null;
  556. }
  557. Application.Restart();
  558. }
  559. }
  560. }
  561. internal static Task RunAsync(this Process process)
  562. {
  563. var tcs = new TaskCompletionSource<object>();
  564. process.EnableRaisingEvents = true;
  565. process.Exited += (s, e) => tcs.TrySetResult(null);
  566. if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
  567. return tcs.Task;
  568. }
  569. internal static PingReply PingHost(string nameOrAddress)
  570. {
  571. PingReply reply;
  572. try
  573. {
  574. addressToPing = Dns.GetHostAddresses(nameOrAddress)
  575. .First(address => address.AddressFamily == AddressFamily.InterNetwork);
  576. reply = pinger.Send(addressToPing);
  577. return reply;
  578. }
  579. catch
  580. {
  581. return null;
  582. }
  583. }
  584. internal static bool IsInternetAvailable()
  585. {
  586. const int timeout = 1000;
  587. const string host = "1.1.1.1";
  588. var ping = new Ping();
  589. var buffer = new byte[32];
  590. var pingOptions = new PingOptions();
  591. try
  592. {
  593. var reply = ping.Send(host, timeout, buffer, pingOptions);
  594. return (reply != null && reply.Status == IPStatus.Success);
  595. }
  596. catch (Exception)
  597. {
  598. return false;
  599. }
  600. }
  601. internal static void FlushDNSCache()
  602. {
  603. Utilities.RunBatchFile(Required.ScriptsFolder + "FlushDNSCache.bat");
  604. //Utilities.RunCommand("ipconfig /release && ipconfig /renew && arp -d * && nbtstat -R && nbtstat -RR && ipconfig /flushdns && ipconfig /registerdns");
  605. }
  606. internal static string SanitizeFileFolderName(string fileName)
  607. {
  608. char[] invalids = Path.GetInvalidFileNameChars();
  609. return string.Join("_", fileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
  610. }
  611. // attempt to enable Local Group Policy Editor on Windows 10 Home editions
  612. internal static void EnableGPEDitor()
  613. {
  614. Utilities.RunBatchFile(Required.ScriptsFolder + "GPEditEnablerInHome.bat");
  615. }
  616. internal static string GetNETFramework()
  617. {
  618. string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";
  619. int netRelease;
  620. using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
  621. {
  622. if (ndpKey != null && ndpKey.GetValue("Release") != null)
  623. {
  624. netRelease = (int)ndpKey.GetValue("Release");
  625. }
  626. else
  627. {
  628. return "4.0";
  629. }
  630. }
  631. if (netRelease >= 528040)
  632. return "4.8";
  633. if (netRelease >= 461808)
  634. return "4.7.2";
  635. if (netRelease >= 461308)
  636. return "4.7.1";
  637. if (netRelease >= 460798)
  638. return "4.7";
  639. if (netRelease >= 394802)
  640. return "4.6.2";
  641. if (netRelease >= 394254)
  642. return "4.6.1";
  643. if (netRelease >= 393295)
  644. return "4.6";
  645. if (netRelease >= 379893)
  646. return "4.5.2";
  647. if (netRelease >= 378675)
  648. return "4.5.1";
  649. if (netRelease >= 378389)
  650. return "4.5";
  651. return "4.0";
  652. }
  653. }
  654. }