public IsInRole ( System.Security.Principal.SecurityIdentifier sid ) : bool | ||
sid | System.Security.Principal.SecurityIdentifier | |
리턴 | bool |
public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); //Create a windowsidentity object representing the current user WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); //Create a windowsprincipal object representing the current user WindowsPrincipal currentprincipal = new WindowsPrincipal(currentIdentity); //Set the security policy context to windows security System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); //hide the subtract and multiply button if user is not and Administrator if(!currentprincipal.IsInRole(WindowsBuiltInRole.Administrator)) { subtractButton.Visible = false; multiplyButton.Visible = false; } //hide the add button if user is not in Users group if(!currentprincipal.IsInRole(WindowsBuiltInRole.User)) { addButton.Visible = false; } //Hide the Divide button if the user is not named CPhilips if(!(currentIdentity.Name.ToLower() == Environment.MachineName.ToLower() + @"\rafa&pri")) { divideButton.Visible = false; } }
public void Execute() { PrintHeader(); var id = WindowsIdentity.GetCurrent(); Console.WriteLine("Identity Id: " + id.Name); var account = new NTAccount(id.Name); var sid = account.Translate(typeof(SecurityIdentifier)); Console.WriteLine("SecurityIdentifier (sid): " + sid.Value); foreach (var group in id.Groups.Translate(typeof(NTAccount))) Console.WriteLine("InGroup: " + group); var principal = new WindowsPrincipal(id); var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins)); var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid); Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins)); Console.WriteLine(); // be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights, // unless the process was run elevated "as Admin". }
/// <summary>Checks if the current process has the necessary permissions to a folder. This allows "custom" elevation of limited users -- allowing them control over normally restricted folders.</summary> /// <param name="folder">The full path to the folder to check.</param> /// <returns>True if the user has permission, false if not.</returns> static bool HaveFolderPermissions(string folder) { try { const FileSystemRights RightsNeeded = FileSystemRights.Traverse | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.ListDirectory | FileSystemRights.CreateFiles | FileSystemRights.CreateDirectories | FileSystemRights.Modify; //Read, ExecuteFile, Write, Delete FileSystemSecurity security = Directory.GetAccessControl(folder); var rules = security.GetAccessRules(true, true, typeof(NTAccount)); var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); FileSystemRights RightsHave = 0; FileSystemRights RightsDontHave = 0; foreach (FileSystemAccessRule rule in rules) { // First check to see if the current user is even in the role, if not, skip if (rule.IdentityReference.Value.StartsWith("S-1-")) { var sid = new SecurityIdentifier(rule.IdentityReference.Value); if (!currentuser.IsInRole(sid)) continue; } else { if (!currentuser.IsInRole(rule.IdentityReference.Value)) continue; } if (rule.AccessControlType == AccessControlType.Deny) RightsDontHave |= rule.FileSystemRights; else RightsHave |= rule.FileSystemRights; } // exclude "RightsDontHave" RightsHave &= ~RightsDontHave; //Note: We're "XOR"ing with RightsNeeded to eliminate permissions that // "RightsHave" and "RightsNeeded" have in common. Then we're // ANDing that result with RightsNeeded to get permissions in // "RightsNeeded" that are missing from "RightsHave". The result // should be 0 if the user has RightsNeeded over the folder (even // if "RightsHave" has flags that aren't present in the // "RightsNeeded" -- which can happen because "RightsNeeded" isn't // *every* possible flag). // Check if the user has full control over the folder. return ((RightsHave ^ RightsNeeded) & RightsNeeded) == 0; } catch { return false; } }
public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity); System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); if (!currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { subtractButton.Visible = false; multiplyButton.Visible = false; } if (!currentPrincipal.IsInRole(WindowsBuiltInRole.User)) addButton.Visible = false; if (!(currentIdentity.Name.ToLower() == System.Environment.MachineName.ToLower() + @"\donal")) divideButton.Visible = false; }
static void Main(string[] args) { try { AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); Console.WriteLine("Getting current principal"); IPrincipal myPrincipal = Thread.CurrentPrincipal; Console.WriteLine("Name: " + myPrincipal.Identity.Name); Console.WriteLine("AuthenicationsType: " + myPrincipal.Identity.AuthenticationType); Console.WriteLine("IsAuthenticated: " + myPrincipal.Identity.IsAuthenticated); Console.WriteLine("\nNow setting principal policy on the app domain to windows."); AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); Console.WriteLine("CurrentPrincipal Type: " + Thread.CurrentPrincipal.GetType()); Console.WriteLine("CurrentPrincipal Name: " + Thread.CurrentPrincipal.Identity.Name); WindowsPrincipal newPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal; Console.WriteLine("Name: " + newPrincipal.Identity.Name); Console.WriteLine("AuthenicationsType: " + newPrincipal.Identity.AuthenticationType); Console.WriteLine("IsAuthenticated: " + newPrincipal.Identity.IsAuthenticated + "\n\n"); WindowsIdentity myIdent = WindowsIdentity.GetCurrent(); Console.WriteLine("Name: " + myIdent.Name); Console.WriteLine("AuthenicationsType: " + myIdent.AuthenticationType); Console.WriteLine("IsAuthenticated: " + myIdent.IsAuthenticated); WindowsPrincipal principal = new WindowsPrincipal(myIdent); if (principal.IsInRole(@"BUILTIN\Administrators")) { Console.WriteLine("You are an administrator"); } else { Console.WriteLine("You are not an administrator"); } if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { Console.WriteLine("You are an administrator"); } else { Console.WriteLine("You are not an administrator"); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private static bool HasDeletePermission(string FilePath) { try { FileSystemSecurity security; if (File.Exists(FilePath)) { security = File.GetAccessControl(FilePath); } else { security = Directory.GetAccessControl(Path.GetDirectoryName(FilePath)); } var rules = security.GetAccessRules(true, true, typeof(NTAccount)); var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool result = false; foreach (FileSystemAccessRule rule in rules) { if (0 == (rule.FileSystemRights & (FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles))) { continue; } if (rule.IdentityReference.Value.StartsWith("S-1-")) { var sid = new SecurityIdentifier(rule.IdentityReference.Value); if (!currentuser.IsInRole(sid)) { continue; } } else { if (!currentuser.IsInRole(rule.IdentityReference.Value)) { continue; } } if (rule.AccessControlType == AccessControlType.Deny) return false; if (rule.AccessControlType == AccessControlType.Allow) result = true; } return result; } catch { return false; } }
public UserGroup calculateUserGroupBasedOnWindowsIdentity() { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); if (principal.IsInRole(adminGroup)) return UserGroup.Admin; if (principal.IsInRole(editorGroup)) return UserGroup.Editor; if (principal.IsInRole(readerGroup)) return UserGroup.Reader; return UserGroup.None; }
public static bool GetHasElevatedPrivileges() { if (!IsWindows8()) return true; var identity = WindowsIdentity.GetCurrent(); if (identity == null) return false; var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); }
//권한 public static string GetAccountType() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return "Admin"; else if (principal.IsInRole(WindowsBuiltInRole.User)) return "User"; else if (principal.IsInRole(WindowsBuiltInRole.Guest)) return "Guest"; else return "Unknown"; }
public static WindowsPrincipal ShowPrincipal(WindowsIdentity identity) { WriteLine("Show principal information"); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal == null) { WriteLine("not a Windows Principal"); return null; } WriteLine($"Users? {principal.IsInRole(WindowsBuiltInRole.User)}"); WriteLine($"Administrators? {principal.IsInRole(WindowsBuiltInRole.Administrator)}"); WriteLine(); return principal; }
protected override bool IsAuthorized(HttpActionContext actionContext) { System.Security.Principal.WindowsPrincipal user = actionContext.RequestContext.Principal as System.Security.Principal.WindowsPrincipal; if (user.IsInRole(WindowsBuiltInRole.Administrator)) { return(true); } if (user.IsInRole(WindowsBuiltInRole.PowerUser)) { return(true); } return(base.IsAuthorized(actionContext)); }
public UserGroup calculateUserGroupBasedOnWindowsIdentity(WindowsIdentity identity) { if (identity != null) { var windowsAuth = TMConfig.Current.WindowsAuthentication; var principal = new WindowsPrincipal(identity); if (principal.IsInRole(windowsAuth.AdminGroup.trim())) return UserGroup.Admin; if (principal.IsInRole(windowsAuth.EditorGroup.trim())) return UserGroup.Editor; if (principal.IsInRole(windowsAuth.ReaderGroup.trim())) return UserGroup.Reader; } return UserGroup.None; }
/// <summary> /// Returns whether the application runs with admin rights or not. /// </summary> public static bool CheckAdmin() { var id = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
/// <summary> /// 检查是否是管理员身份 /// </summary> private void CheckAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { // It is not possible to launch a ClickOnce app as administrator directly, // so instead we launch the app as administrator in a new process. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator processInfo.UseShellExecute = true; processInfo.Verb = "runas"; // Start the new process try { Process.Start(processInfo); } catch { MessageBox.Show("没有管理员权限\n请右键该程序之后点击“以管理员权限运行”"); } // Shut down the current process Environment.Exit(0); } }
public static bool IsUserAdministrator() { bool isAdmin; WindowsIdentity user = null; try { //get the currently logged in user user = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(user); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch (UnauthorizedAccessException) { isAdmin = false; } catch (Exception) { isAdmin = false; } finally { if (user != null) user.Dispose(); } return isAdmin; }
private static bool IsAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(id); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); return isAdmin; }
static void Main() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (hasAdministrativeRight == false) { ProcessStartInfo processInfo = new ProcessStartInfo(); //создаем новый процесс processInfo.Verb = "runas"; //в данном случае указываем, что процесс должен быть запущен с правами администратора processInfo.FileName = Application.ExecutablePath; //указываем исполняемый файл (программу) для запуска try { Process.Start(processInfo); //пытаемся запустить процесс } catch (Win32Exception) { //Ничего не делаем, потому что пользователь, возможно, нажал кнопку "Нет" в ответ на вопрос о запуске программы в окне предупреждения UAC (для Windows 7) } Application.Exit(); //закрываем текущую копию программы (в любом случае, даже если пользователь отменил запуск с правами администратора в окне UAC) } else //имеем права администратора, значит, стартуем { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } }
private void mainForm_Load(object sender, EventArgs e) { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { // relaunch the application with admin rights string fileName = Assembly.GetExecutingAssembly().Location; ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = fileName; try { Process.Start(processInfo); } catch (Win32Exception) { this.Close(); } return; } this.BringToFront(); updateStats(); }
private static bool IsRunningAsRoot() { if (MonoHelper.RunningOnMono) { return MonoHelper.RunningAsRoot; } try { // Этот код также работает под Mono/Linux, но есть сомнения, что под любой платформой var user = WindowsIdentity.GetCurrent(); if (user != null) { var principal = new WindowsPrincipal(user); return principal.IsInRole(WindowsBuiltInRole.Administrator); } } catch (Exception) { } return false; }
public int Set(int index) { Process newProcess = ProcessesList[index]; if (newProcess.StartInfo.UseShellExecute) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); canRun = principal.IsInRole(WindowsBuiltInRole.Administrator); } if (canRun) { if (SelectedProcess == null || newProcess.MainWindowHandle != SelectedProcess.MainWindowHandle) { if (SelectedProcess != null) SelectedProcess.Exited -= new EventHandler(ExitCallback); if (SelectedProcess != null && newProcess.Id != SelectedProcess.Id) ShowWindow(newProcess.MainWindowHandle); SelectedProcess = newProcess; SelectedProcess.EnableRaisingEvents = true; SelectedProcess.Exited += new EventHandler(ExitCallback); } return SelectedProcess.Id; } WindowClosedEvent(true, "Run as Administrator!"); return -1; }
public static bool IsAdministrator() { var winId = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(winId); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
public static bool IsInRole(string role) { var windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity == null) return false; var principal = new WindowsPrincipal(windowsIdentity); return principal.IsInRole(role); }
/// <summary> /// Elevate application rights to Administrator. This will cause a UAC box to pop up. /// </summary> /// <param name="createWindow">Run the elevated process in a new window.</param> /// <returns>True or false depending on succesful elevation.</returns> public bool ElevateRights(bool createWindow) { try { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); if (isAdmin) { return true; } else { // basically: give this application admin rights ProcessStartInfo psiElev = new ProcessStartInfo(); psiElev.Verb = "runas"; psiElev.UserName = null; psiElev.Password = null; psiElev.FileName = Assembly.GetExecutingAssembly().Location; psiElev.CreateNoWindow = createWindow; Process pElev = Process.Start(psiElev); return true; } } catch (Exception) { return false; } }
private static bool IsRunAsAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); return wp.IsInRole(WindowsBuiltInRole.Administrator); }
public CounterControl() { // Check user is Administrator and has granted UAC elevation permission to run this app var userIdent = WindowsIdentity.GetCurrent(); var userPrincipal = new WindowsPrincipal(userIdent); IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator); }
public static bool RunAsAdministrator(string[] Args) { //获得当前登录的Windows用户标示 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判断当前登录用户是否为管理员 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { return(true); } else { //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); //设置运行文件 startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; //设置启动参数 startInfo.Arguments = String.Join(" ", Args); //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; //如果不是管理员,则启动UAC System.Diagnostics.Process.Start(startInfo); //退出 System.Windows.Forms.Application.Exit(); return(false); } }
private void CheckUAC() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!pricipal.IsInRole(WindowsBuiltInRole.Administrator)) { buttonInstallFiles.Enabled = false; buttonUninstallFiles.Enabled = false; buttonInstallFolders.Enabled = false; buttonUninstallFolders.Enabled = false; MessageBox.Show("UAC is preventing this action to complete. Restarting as administrator."); ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = Application.ExecutablePath; try { Process.Start(processInfo); Application.Exit(); } catch (Win32Exception) { //Do nothing. Probably the user canceled the UAC window } } }
/// <summary> /// This routine should be called automatically by the MSI during setup, but it can also be called using: /// "installutil.exe Archiver.dll" /// </summary> /// <param name="savedState">State dictionary passed in by the installer code</param> public override void Install (IDictionary savedState) { #region Check to make sure we're in an Administrator role WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (wp.IsInRole(WindowsBuiltInRole.Administrator) == false) { MessageBox.Show("You must be an Administrator to install Rtp or run it for the first time.", "Administrator Privileges Required", MessageBoxButtons.OK, MessageBoxIcon.Stop); Application.Exit(); } #endregion #region Uninstall in case we weren't uninstalled cleanly before IDictionary state = new Hashtable(); Uninstall(state); if (state.Count != 0) Commit(state); state = null; #endregion #region Call base.Install base.Install(savedState); #endregion #region Install the Event Logs ArchiveServiceEventLog.Install(); #endregion #region Create PerfCounters PCInstaller.Install(); #endregion #region Save the fact that we're installed to the registry Installed = true; #endregion }
public static bool CheckUserRights(string userLogin, string rightName) { string programName = WebConfigurationManager.AppSettings["progName"]; bool flag = false; SqlParameter pProgramName = new SqlParameter() { ParameterName = "program_name", Value = programName, DbType = DbType.AnsiString }; SqlParameter pRightName = new SqlParameter() { ParameterName = "sys_name", Value = rightName, DbType = DbType.AnsiString }; DataTable dt = new DataTable(); dt = ExecuteQueryStoredProcedure(sp, "getUserGroupSid", pProgramName, pRightName); if (dt.Rows.Count > 0) { DataRow dr = dt.Rows[0]; string sid = dr["sid"].ToString(); try { WindowsIdentity wi = new WindowsIdentity(userLogin); WindowsPrincipal wp = new WindowsPrincipal(wi); SecurityIdentifier grpSid = new SecurityIdentifier(sid); flag = wp.IsInRole(grpSid); } catch (Exception ex) { flag = false; } } return flag; }
private static bool isAdministrator() { SimpleLogger.Instance().WriteLine("Checking privileges..."); WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
private void Apply_Click(object sender, RoutedEventArgs e) { Config.IconSize = (int)Math.Round(slIconSize.Value); Config.GridMaximumCols = (int)Math.Round(slGridCols.Value); Config.GridMaximumRows = (int)Math.Round(slGridRows.Value); Config.HideDelay = (int)Math.Round(slHideDelay.Value); Config.PopupDelay = (int)Math.Round(slPopupDelay.Value); Config.HoverEnabled = (int)Math.Round(slHoverEnabled.Value) != 0; Config.HoverTextEnabled = (int)Math.Round(slHoverTextEnabled.Value) != 0; Config.HoverHideDelay = (int)Math.Round(slHoverHideDelay.Value); Config.HoverMoveDealy = (int)Math.Round(slHoverMoveDelay.Value); Config.HoverPopupDelay = (int)Math.Round(slHoverPopupDelay.Value); var id = WindowsIdentity.GetCurrent(); var wPrincipal = new WindowsPrincipal(id); if (wPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { Config.Save(); } else { var myProcess = new ProcessStartInfo(System.Windows.Forms.Application.ExecutablePath); myProcess.Verb = "runas"; myProcess.Arguments = string.Format("-p {0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", Config.IconSize, Config.GridMaximumCols, Config.GridMaximumRows, Config.HideDelay, Config.PopupDelay, Config.HoverEnabled, Config.HoverHideDelay, Config.HoverMoveDealy, Config.HoverPopupDelay, Config.HoverTextEnabled); Process.Start(myProcess); Close(); } }
ConsoleHostRawUserInterface(ConsoleHostUserInterface mshConsole) : base() { defaultForeground = ForegroundColor; defaultBackground = BackgroundColor; parent = mshConsole; // cacheKeyEvent is a value type and initialized automatically // add "Administrator: " prefix into the window title, but don't wait for it to finish // (we may load resources which can take some time) Task.Run(() => { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; // check using Regex if the window already has Administrator: prefix // (i.e. from the parent console process) string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate; titlePattern = Regex.Escape(titlePattern) .Replace(@"\{1}", ".*") .Replace(@"\{0}", Regex.Escape(prefix)); if (!Regex.IsMatch(this.WindowTitle, titlePattern)) { this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate, prefix, this.WindowTitle); } } }); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); /** * 当前用户是管理员的时候,直接启动应用程序 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 */ //获得当前登录的Windows用户标示 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判断当前登录用户是否为管理员 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { //如果是管理员,则直接运行 Application.Run(new FrmMain()); } else { //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; startInfo.FileName = Application.ExecutablePath; //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; try { System.Diagnostics.Process.Start(startInfo); } catch { return; } //退出 Application.Exit(); } }
static void Main(string[] args) { System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid); Console.WriteLine(printcipal.Identity.AuthenticationType); using (Impersonator i = new Impersonator("andy2", ".", "andy2")) { Console.WriteLine(WindowsIdentity.GetCurrent().Name); System.Security.Principal.WindowsIdentity wid2 = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal printcipal2 = new System.Security.Principal.WindowsPrincipal(wid2); Console.WriteLine(printcipal2.Identity.AuthenticationType); bool isAdmin = (printcipal2.IsInRole(@"BUILTIN\Administrators")); Console.WriteLine(isAdmin); } //WindowsIdentity.Impersonate(IntPtr.Zero); //Console.WriteLine(WindowsIdentity.GetCurrent().Name); //System.Security.Principal.WindowsIdentity wid = System.Security.Principal.WindowsIdentity.GetCurrent(); // System.Security.Principal.WindowsPrincipal printcipal = new System.Security.Principal.WindowsPrincipal(wid); // bool isAdmin = (printcipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); // Console.WriteLine(isAdmin); }
public static bool QP() { /** * 当前用户是管理员的时候,直接启动应用程序 * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行 */ //获得当前登录的Windows用户标示 System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); //创建Windows用户主题 Application.EnableVisualStyles(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); //判断当前登录用户是否为管理员 if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { //如果是管理员,则直接运行 Application.EnableVisualStyles(); return(true); } else { //创建启动对象 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); //设置运行文件 startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; //设置启动参数 startInfo.Arguments = String.Join("", new string[0]); //设置启动动作,确保以管理员身份运行 startInfo.Verb = "runas"; //如果不是管理员,则启动UAC System.Diagnostics.Process.Start(startInfo); //退出 System.Windows.Forms.Application.Exit(); } return(false); }
static bool ihInteg() { System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); return(principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); if (mutex.WaitOne(TimeSpan.Zero, true)) { #if DEBUG Global.isDebug = true; #endif Global.Initialize(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Directory.SetCurrentDirectory(path); string logiDll = Path.Combine(path, "LogitechLed.dll"); if (File.Exists(logiDll)) { File.Delete(logiDll); } StringBuilder systeminfo_sb = new StringBuilder(string.Empty); systeminfo_sb.Append("\r\n========================================\r\n"); try { var win_reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); string productName = (string)win_reg.GetValue("ProductName"); systeminfo_sb.AppendFormat("Operation System: {0}\r\n", productName); } catch (Exception exc) { systeminfo_sb.AppendFormat("Operation System: Could not be retrieved. [Exception: {0}]\r\n", exc.Message); } systeminfo_sb.AppendFormat("System Architecture: " + (Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit") + "\r\n"); systeminfo_sb.AppendFormat("Environment OS Version: {0}\r\n", Environment.OSVersion); systeminfo_sb.AppendFormat("System Directory: {0}\r\n", Environment.SystemDirectory); systeminfo_sb.AppendFormat("Executing Directory: {0}\r\n", Global.ExecutingDirectory); systeminfo_sb.AppendFormat("Launch Directory: {0}\r\n", Directory.GetCurrentDirectory()); systeminfo_sb.AppendFormat("Processor Count: {0}\r\n", Environment.ProcessorCount); //systeminfo_sb.AppendFormat("User DomainName: {0}\r\n", Environment.UserDomainName); //systeminfo_sb.AppendFormat("User Name: {0}\r\n", Environment.UserName); systeminfo_sb.AppendFormat("SystemPageSize: {0}\r\n", Environment.SystemPageSize); systeminfo_sb.AppendFormat("Environment Version: {0}\r\n", Environment.Version); System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity); systeminfo_sb.AppendFormat("Is Elevated: {0}\r\n", principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)); systeminfo_sb.AppendFormat("Aurora Assembly Version: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); systeminfo_sb.AppendFormat("Aurora File Version: {0}\r\n", System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion); systeminfo_sb.Append("========================================\r\n"); Global.logger.Info(systeminfo_sb.ToString()); string arg = ""; for (int arg_i = 0; arg_i < e.Args.Length; arg_i++) { arg = e.Args[arg_i]; switch (arg) { case ("-debug"): Global.isDebug = true; Global.logger.Info("Program started in debug mode."); break; case ("-silent"): isSilent = true; Global.logger.Info("Program started with '-silent' parameter"); break; case ("-ignore_update"): ignore_update = true; Global.logger.Info("Program started with '-ignore_update' parameter"); break; case ("-delay"): isDelayed = true; if (arg_i + 1 < e.Args.Length && int.TryParse(e.Args[arg_i + 1], out delayTime)) { arg_i++; } else { delayTime = 5000; } Global.logger.Info("Program started with '-delay' parameter with delay of " + delayTime + " ms"); break; case ("-install_logitech"): Global.logger.Info("Program started with '-install_logitech' parameter"); try { InstallLogitech(); } catch (Exception exc) { System.Windows.MessageBox.Show("Could not patch Logitech LED SDK. Error: \r\n\r\n" + exc, "Aurora Error"); } Environment.Exit(0); break; } } AppDomain currentDomain = AppDomain.CurrentDomain; if (!Global.isDebug) { currentDomain.UnhandledException += CurrentDomain_UnhandledException; } if (isDelayed) { System.Threading.Thread.Sleep((int)delayTime); } this.ShutdownMode = ShutdownMode.OnExplicitShutdown; //AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); if (Environment.Is64BitProcess) { currentDomain.AppendPrivatePath("x64"); } else { currentDomain.AppendPrivatePath("x86"); } Global.StartTime = Utils.Time.GetMillisecondsSinceEpoch(); Global.dev_manager = new DeviceManager(); Global.effengine = new Effects(); //Load config Global.logger.Info("Loading Configuration"); try { Global.Configuration = ConfigManager.Load(); } catch (Exception exc) { Global.logger.Error("Exception during ConfigManager.Load(). Error: " + exc); System.Windows.MessageBox.Show("Exception during ConfigManager.Load().Error: " + exc.Message + "\r\n\r\n Default configuration loaded.", "Aurora - Error"); Global.Configuration = new Configuration(); } Global.Configuration.PropertyChanged += (sender, eventArgs) => { ConfigManager.Save(Global.Configuration); }; Process.GetCurrentProcess().PriorityClass = Global.Configuration.HighPriority ? ProcessPriorityClass.High : ProcessPriorityClass.Normal; if (Global.Configuration.updates_check_on_start_up && !ignore_update) { string updater_path = System.IO.Path.Combine(Global.ExecutingDirectory, "Aurora-Updater.exe"); if (File.Exists(updater_path)) { try { ProcessStartInfo updaterProc = new ProcessStartInfo(); updaterProc.FileName = updater_path; updaterProc.Arguments = "-silent"; Process.Start(updaterProc); } catch (Exception exc) { Global.logger.Error("Could not start Aurora Updater. Error: " + exc); } } } Global.logger.Info("Loading Plugins"); (Global.PluginManager = new PluginManager()).Initialize(); Global.logger.Info("Loading KB Layouts"); Global.kbLayout = new KeyboardLayoutManager(); Global.kbLayout.LoadBrandDefault(); Global.logger.Info("Loading Input Hooking"); Global.InputEvents = new InputEvents(); Global.Configuration.PropertyChanged += SetupVolumeAsBrightness; SetupVolumeAsBrightness(Global.Configuration, new PropertyChangedEventArgs(nameof(Global.Configuration.UseVolumeAsBrightness))); Utils.DesktopUtils.StartSessionWatch(); Global.key_recorder = new KeyRecorder(Global.InputEvents); Global.logger.Info("Loading RazerSdkManager"); if (RzHelper.IsSdkVersionSupported(RzHelper.GetSdkVersion())) { try { Global.razerSdkManager = new RzSdkManager() { KeyboardEnabled = true, MouseEnabled = true, MousepadEnabled = true, AppListEnabled = true, }; Global.logger.Info("RazerSdkManager loaded successfully!"); } catch (Exception exc) { Global.logger.Fatal("RazerSdkManager failed to load!"); Global.logger.Fatal(exc.ToString()); } } else { Global.logger.Warn("Currently installed razer sdk version \"{0}\" is not supported by the RazerSdkManager!", RzHelper.GetSdkVersion()); } Global.logger.Info("Loading Applications"); (Global.LightingStateManager = new LightingStateManager()).Initialize(); if (Global.Configuration.GetPointerUpdates) { Global.logger.Info("Fetching latest pointers"); Task.Run(() => Utils.PointerUpdateUtils.FetchDevPointers("master")); } Global.logger.Info("Loading Device Manager"); Global.dev_manager.RegisterVariables(); Global.dev_manager.Initialize(); /*Global.logger.LogLine("Starting GameEventHandler", Logging_Level.Info); * Global.geh = new GameEventHandler(); * if (!Global.geh.Init()) * { * Global.logger.LogLine("GameEventHander could not initialize", Logging_Level.Error); * return; * }*/ Global.logger.Info("Starting GameStateListener"); try { Global.net_listener = new NetworkListener(9088); Global.net_listener.NewGameState += new NewGameStateHandler(Global.LightingStateManager.GameStateUpdate); Global.net_listener.WrapperConnectionClosed += new WrapperConnectionClosedHandler(Global.LightingStateManager.ResetGameState); } catch (Exception exc) { Global.logger.Error("GameStateListener Exception, " + exc); System.Windows.MessageBox.Show("GameStateListener Exception.\r\n" + exc); Environment.Exit(0); } if (!Global.net_listener.Start()) { Global.logger.Error("GameStateListener could not start"); System.Windows.MessageBox.Show("GameStateListener could not start. Try running this program as Administrator.\r\nExiting."); Environment.Exit(0); } Global.logger.Info("Listening for game integration calls..."); Global.logger.Info("Loading ResourceDictionaries..."); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Core.Implicit.xaml", UriKind.Relative) }); this.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("Themes/MetroDark/MetroDark.MSControls.Toolkit.Implicit.xaml", UriKind.Relative) }); Global.logger.Info("Loaded ResourceDictionaries"); Global.logger.Info("Loading ConfigUI..."); MainWindow = new ConfigUI(); ((ConfigUI)MainWindow).Display(); //Debug Windows on Startup if (Global.Configuration.BitmapWindowOnStartUp) { Window_BitmapView.Open(); } if (Global.Configuration.HttpWindowOnStartUp) { Window_GSIHttpDebug.Open(); } } else { try { NamedPipeClientStream client = new NamedPipeClientStream(".", "aurora\\interface", PipeDirection.Out); client.Connect(30); if (!client.IsConnected) { throw new Exception(); } byte[] command = System.Text.Encoding.ASCII.GetBytes("restore"); client.Write(command, 0, command.Length); client.Close(); } catch { //Global.logger.LogLine("Aurora is already running.", Logging_Level.Error); System.Windows.MessageBox.Show("Aurora is already running.\r\nExiting.", "Aurora - Error"); } } }
private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()); if (!windowsPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.NeedPrivilege, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); System.Environment.Exit(0); return; } EcoGlobalVar.nullcontextMenuStrip = new ContextMenuStrip(); EcoGlobalVar.ECOAppRunMode = 1; AppInterProcess.OpenInterProcessShared(); int processID = AppInterProcess.getProcessID(Program.program_uid, Program.program_serverid, EcoGlobalVar.ECOAppRunMode); if (processID != 0) { AppInterProcess.CloseShared(); string processOwner = Program.GetProcessOwner(processID); string processOwner2 = Program.GetProcessOwner(Process.GetCurrentProcess().Id); if (processOwner.Equals(processOwner2)) { Program.setTopMost(processID); } else { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.APPRunbyuser, new string[] { processOwner }), "Information", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } System.Environment.Exit(0); return; } AppInterProcess.setMyProcessID(Program.program_uid, Program.program_serverid, EcoGlobalVar.ECOAppRunMode); Program.setTopMost(Process.GetCurrentProcess().Id); int mySQLUseMajorVersionOnly = DevAccessCfg.GetInstance().getMySQLUseMajorVersionOnly(); DBMaintain.SetMySQLVersionRole(mySQLUseMajorVersionOnly); while (Program.LocalConsole_cfg() == -2) { } DBUrl.RUNMODE = 1; ClientAPI.SetBroadcastCallback(new CommonAPI.CommonAPI.DelegateOnBroadcast(EcoGlobalVar.receiveDashBoardFlgProc)); ClientAPI.SetClosedCallback(new CommonAPI.CommonAPI.DelegateOnClosed(EcoGlobalVar.ServerClosedProc)); Login.Login login = new Login.Login(); login.Icon = null; login.ShowDialog(); if (login.UserName == null) { Program.ExitApp(); return; } EcoGlobalVar.gl_StartProcessfThread(true); Application.CurrentCulture = System.Globalization.CultureInfo.CurrentUICulture; if (EcoGlobalVar.ECOAppRunMode == 1) { DBCacheStatus.DBSyncEventInit(false); DBCacheEventProcess.StartRefreshThread(false); DBCache.DBCacheInit(false); } if (ClientAPI.WaitDatasetReady(40000u) < 0) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.DB_waitready, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.ExitApp(); return; } EcoGlobalVar.DCLayoutType = ClientAPI.getRackLayout(); EcoGlobalVar.gl_maxZoneNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxZoneNum")); EcoGlobalVar.gl_maxRackNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxRackNum")); EcoGlobalVar.gl_maxDevNum = CultureTransfer.ToInt32(ClientAPI.getKeyValue("MaxDevNum")); EcoGlobalVar.gl_supportISG = (CultureTransfer.ToInt32(ClientAPI.getKeyValue("SupportISG")) > 0); EcoGlobalVar.gl_supportBP = (CultureTransfer.ToInt32(ClientAPI.getKeyValue("SupportBP")) > 0); EcoGlobalVar.TempUnit = CultureTransfer.ToInt32(ClientAPI.getKeyValue("TempUnit")); EcoGlobalVar.CurCurrency = ClientAPI.getKeyValue("CurCurrency"); EcoGlobalVar.co2kg = CultureTransfer.ToSingle(ClientAPI.getKeyValue("co2kg")); EcoGlobalVar.flgEnablePower = AppData.getDB_flgEnablePower(); EcoGlobalVar.RackFullNameFlag = CultureTransfer.ToInt32(ClientAPI.getKeyValue("RackFullNameFlag")); EcoGlobalVar.gl_PeakPowerMethod = DevAccessCfg.GetInstance().getPowerPeakMethod(); string valuePair = ValuePairs.getValuePair("UserID"); long l_id = System.Convert.ToInt64(valuePair); string valuePair2 = ValuePairs.getValuePair("UserName"); valuePair = ValuePairs.getValuePair("UserType"); int i_type = System.Convert.ToInt32(valuePair); valuePair = ValuePairs.getValuePair("UserRight"); int i_right = System.Convert.ToInt32(valuePair); string valuePair3 = ValuePairs.getValuePair("UserPortNM"); string valuePair4 = ValuePairs.getValuePair("UserDevice"); string valuePair5 = ValuePairs.getValuePair("UserGroup"); valuePair = ValuePairs.getValuePair("UserStatus"); ValuePairs.getValuePair("trial"); ValuePairs.getValuePair("remaining_days"); int i_status = System.Convert.ToInt32(valuePair); UserInfo userInfo = new UserInfo(l_id, valuePair2, "", i_status, i_type, i_right, valuePair3, valuePair4, valuePair5); EcoGlobalVar.gl_LoginUser = userInfo; EcoGlobalVar.gl_LoginUserUACDev2Port = (System.Collections.Generic.Dictionary <long, System.Collections.Generic.List <long> >)ClientAPI.RemoteCall(8, 1, "", 10000); if (EcoGlobalVar.gl_LoginUserUACDev2Port == null) { TopMostMessageBox.Show(EcoLanguage.getMsg(LangRes.DB_waitready, new string[0]), "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); Program.ExitApp(); return; } string para = "0230000\n" + userInfo.UserName; ClientAPI.RemoteCall(100, 1, para, 10000); MainForm.MainForm mainForm = new MainForm.MainForm(userInfo); EcoGlobalVar.gl_mainForm = mainForm; if (!EcoGlobalVar.gl_supportISG) { EcoGlobalVar.gl_monitorCtrl.FreshFlg_ISGPower = 0; EcoGlobalVar.gl_DashBoardCtrl.FreshFlg_ISGPower = 0; } EcoGlobalVar.gl_StopProcessfThread(); Program.IdleTimer_init(); Application.ApplicationExit += new System.EventHandler(Program.Application_ApplicationExit); System.AppDomain.CurrentDomain.ProcessExit += new System.EventHandler(Program.CurrentDomain_ProcessExit); Application.Run(mainForm); }