/// <summary> /// Restarts the current process with highest privileges. /// </summary> /// <param name="cmdLineArgs"> /// The command-line arguments to use when starting the application. Use null /// to use the current arguments, which are already in use. /// </param> public static void RestartAsAdministrator(string cmdLineArgs = null) { if (IsAdministrator) { return; } var args = string.Empty; if (cmdLineArgs != null) { args = cmdLineArgs; } else { if (Log.DebugMode > 0) { args = $"/{Log.DebugKey} {Log.DebugMode} "; } args += EnvironmentEx.CommandLine(false); } using (ProcessEx.Start(PathEx.LocalPath, PathEx.LocalDir, args, true)) { Environment.ExitCode = 0; Environment.Exit(Environment.ExitCode); } }
/// <summary> /// Restarts the current process with non-elevated privileges. /// </summary> /// <param name="cmdLineArgs"> /// The command-line arguments to use when starting the application. Use null /// to use the current arguments, which are already in use. /// </param> public static void RestartAsNonAdministrator(string cmdLineArgs = null) { if (!IsAdministrator) { return; } var startArgs = string.Empty; if (cmdLineArgs != null) { startArgs = cmdLineArgs; } else { if (Log.DebugMode > 0) { startArgs = $"/{Log.DebugKey} {Log.DebugMode} "; } startArgs += EnvironmentEx.CommandLine(false); } var psi = new ProcessStartInfo { Arguments = startArgs, FileName = PathEx.LocalPath, Verb = "RunNotAs" }; using (ProcessEx.Start(psi)) { Environment.ExitCode = 0; Environment.Exit(Environment.ExitCode); } }
private void Button_Click(object sender, EventArgs e) { if (!(ParentForm is IconBrowserDialog dialog)) { return; } if (int.TryParse(_button.Text, out var index)) { var path = EnvironmentEx.GetVariablePathFull(_file, false, false); dialog.IconPath = path; if (path.Any(char.IsSeparator)) { path = $"\"{path}\""; } dialog.IconId = index; dialog.Text = $@"{path},{index}"; } dialog.Close(); }
/// <summary> /// Combines a <see cref="Environment.SpecialFolder"/> constant with an array of /// strings into a valid path. /// </summary> /// <param name="invalidPathChars"> /// A sequence of invalid chars used as a filter. /// </param> /// <param name="specialFolder"> /// A specified enumerated constant used to retrieve directory paths to system /// special folders. /// </param> /// <param name="paths"> /// An array of parts of the path. /// </param> public static string Combine(char[] invalidPathChars, Environment.SpecialFolder?specialFolder, params string[] paths) { var path = string.Empty; try { if (specialFolder != null) { path = Environment.GetFolderPath((Environment.SpecialFolder)specialFolder); } var separators = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; if (!(paths?.Join(Path.DirectorySeparatorChar).Split(separators, StringSplitOptions.RemoveEmptyEntries) is IEnumerable <string> plains)) { throw new ArgumentNullException(nameof(paths)); } if (invalidPathChars?.Any() ?? false) { plains = plains.Select(x => x.RemoveChar(invalidPathChars)); } path = !string.IsNullOrEmpty(path) ? Path.Combine(path, plains.Join(Path.DirectorySeparatorChar)) : plains.Join(Path.DirectorySeparatorChar); string key = null; byte num = 0; if (path.StartsWith("%", StringComparison.Ordinal) && (path.Contains($"%{Path.DirectorySeparatorChar}") || path.EndsWith("%", StringComparison.Ordinal))) { var regex = Regex.Match(path, "%(.+?)%", RegexOptions.IgnoreCase); if (regex.Groups.Count > 1) { var variable1 = regex.Groups[1].Value; var variable2 = variable1; EnvironmentEx.VariableFilter(ref variable2, out key, out num); if (!string.IsNullOrEmpty(variable2)) { var value = EnvironmentEx.GetVariableValue(variable2); if (!string.IsNullOrEmpty(value)) { path = path.Replace($"%{variable1}%", value); } } } } if (path.Contains($"{Path.DirectorySeparatorChar}..")) { path = Path.GetFullPath(path); } if (path.EndsWith(".", StringComparison.Ordinal)) { path = path.TrimEnd('.'); } if (!string.IsNullOrEmpty(key) || num > 1) { if (string.IsNullOrEmpty(key)) { path = path.Replace(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), new string(Path.DirectorySeparatorChar, num)); } else if (key.EqualsEx("Alt")) { path = path.Replace(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), new string(Path.AltDirectorySeparatorChar, num)); } } } catch (ArgumentException ex) { if (Log.DebugMode > 1) { Log.Write(ex); } } catch (Exception ex) when(ex.IsCaught()) { Log.Write(ex); } return(path); }
private static bool PinUnpin(string path, bool pin) { if (string.IsNullOrWhiteSpace(path)) { return(false); } var file = PathEx.Combine(path); if (!File.Exists(file)) { return(false); } if (IsPinned(file) == pin) { return(true); } var isPresentWindows = Environment.OSVersion.Version.Major >= 10; var shellKeyPath = default(string); try { if (isPresentWindows) { //ProcessEx.CurrentPrincipal.ChangeName("explorer.exe"); throw new NotSupportedException(); } dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application")); var dir = shell.NameSpace(Path.GetDirectoryName(path)); var name = Path.GetFileName(path); var link = dir.ParseName(name); var verbs = link.Verbs(); var sb = new StringBuilder(byte.MaxValue); var lib = WinApi.NativeMethods.LoadLibrary(WinApi.DllNames.Shell32); _ = WinApi.NativeMethods.LoadString(lib, pin ? 0x150au : 0x150bu, sb, 0xff); var verb = sb.ToStringThenClear(); /* * if (!isPresentWindows) * { */ var applied = false; for (var i = 0; i < verbs.Count(); i++) { var e = verbs.Item(i); if ((pin || !e.Name.ContainsEx(verb)) && (!pin || !e.Name.EqualsEx(verb))) { continue; } e.DoIt(); applied = true; break; } if (applied) { goto Done; } //} if (string.IsNullOrWhiteSpace(verb)) { verb = "Toggle Taskbar Pin"; } const string cmdKeyPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\CommandStore\\shell\\Windows.taskbarpin"; var cmdHandler = Reg.ReadString(Registry.LocalMachine, cmdKeyPath, "ExplorerCommandHandler"); if (!string.IsNullOrEmpty(cmdHandler)) { shellKeyPath = $"Software\\Classes\\*\\shell\\{verb}"; Reg.Write(Registry.CurrentUser, shellKeyPath, "ExplorerCommandHandler", cmdHandler); } if (Reg.EntryExists(Registry.CurrentUser, shellKeyPath, "ExplorerCommandHandler")) { link.InvokeVerb(verb); } Done: if (!pin) { return(!IsPinned(file)); } var curLink = GetPinLink(path); if (!File.Exists(curLink)) { return(false); } var target = ShellLink.GetTarget(curLink); var envVar = EnvironmentEx.GetVariableWithPath(target, false, false); if (!target.EqualsEx(envVar)) { FileEx.CreateShellLink(file, curLink); } return(true); } catch (Exception ex) when(ex.IsCaught()) { Log.Write(ex); return(false); } finally { /* * if (isPresentWindows) * ProcessEx.CurrentPrincipal.RestoreName(); */ if (!string.IsNullOrEmpty(shellKeyPath)) { Reg.RemoveSubKey(Registry.CurrentUser, shellKeyPath); } } }