0

Purely for reasons of my own curiosity, I am attempting to create a console application in c# that will elevate itself if it sees that it is not running as admin.

The code that I have at the moment is as follows:

using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;

namespace SelfElevator
{
    class Program
    {
        static void Main(string[] args)
        {
            if (!IsAdmin())
            {
                ProcessStartInfo proc = new()
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = Assembly.GetEntryAssembly().Location,
                    Verb = "runas"
                };

                try
                {
                    Process.Start(proc);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }

        private static bool IsAdmin()
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new(id);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
    }
}

When I attempt to execute this I receive the error "No application is associated with the specified file for this operation."

I have done some googling and have concluded that perhaps this might be connected to the use of the runas verb. How and why (and what I might do to correct) though is still eluding me. Note that I am explicitly not including an application.manifest as I want the application to start unprivileged, detect that it is in that state then restart itself elevated. I also do not mind dealing with the appearance of a UAC prompt. I'm not trying to hack systems - I would just like to understand how to accomplish this process.

Michael Jordan
  • 382
  • 2
  • 13
  • A Net application running in VS will not run As Admin by default. The executable will. To start VS with As admin right click the shortcut and select Run As Admin. – jdweng Jun 06 '21 at 15:54
  • @OlivierRogier your link provided the answer. If you would like to post a solution I will be happy to accept it. – Michael Jordan Jun 06 '21 at 16:11

0 Answers0