Account A is not an administrator, so log in to the WINDOWS system with account A
Account B has administrator authority.
Functions that need to be implemented: I use account A to log in to the windows system and execute the program. At this time, it prompts that I need to execute it with administrator privileges, but I have the administrator user name and password. I need the program to automatically log in and run the program with my administrator account.
But now I use the built-in B account in the program code. After running, the program keeps creating new processes and enters an endless loop. Why?
Porgrams.cs
public static class Program
{
/// <summary>
///
/// </summary>
[STAThread]
static void Main()
{
if (!IsRunAsAdmin())
{
RestartAsAdmin();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
private static bool IsRunAsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
private static void RestartAsAdmin()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.UserName = "li"; // administrator account
startInfo.Password = CreateSecureString("123"); // administrator password
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch (System.ComponentModel.Win32Exception)
{
return;
}
Application.Exit();
}
private static SecureString CreateSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (char c in str)
{
secureString.AppendChar(c);
}
return secureString;
}
}