Reputation: 24116
I have a winform application with the following code in Program.cs
to make sure my app is always running with administrative privilege:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Init visual styles
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Check if app is launched with administrative privilage
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
// Check if application is already running
bool mutexCheck;
var mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetType().GUID.ToString(), out mutexCheck);
if (!mutexCheck)
{
// Error
Utils.ShowError("Program is already running.");
return;
}
// If app is running without administrative privilage
if (!administrativeMode)
{
// Request administrative privilage
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.FileName = Application.ExecutablePath;
try
{
// Run app as administrator
Process.Start(startInfo);
}
catch (Exception ex)
{
// Error
Utils.ShowError("Program failed to start - " + ex.Message);
return;
}
}
return;
// Launch application
Application.Run(new MyApp());
GC.KeepAlive(mutex);
}
}
Every time I press F5
to run the app in debug mode in Visual Studio 2015, the app appears to be just running - the debug environment is not launching.
So, what I have to do is go to Debug -> Attach to Process...
and select MyApp.exe
and then I am prompted with this window:
Then when I click on Restart under different credentials
- VS2015 restarts. I will then have to close the already running instance of MyApp and then press F5
to re-launch with elevated privilege; when I do - the debug works.
Is there a way to set my VS2015 to always run this project with elevated privilege?
Upvotes: 1
Views: 2273
Reputation: 125197
Try running your Visual Studio as Administrator. In the cases that I faced with insufficient privileges Running Visual Studio As Administrator has fixed my problem.
Upvotes: 2