SammuelMiranda SammuelMiranda - 2 months ago 12
C# Question

Start a Service thought ASP.net Page

I wrote a windows service, that works perfectly. It is call (on Command Prompt) via

ChatServer.exe {argument}
where the
{argument}
is a key work such as
install
,
uninstall
,
start
and
stop
.

The program where this service is require administrative privileges (since it install/uninstall itself). So if i start
cmd
as administrator
"D:\folder\chatserver.exe install"
for example, it install the service as it should.

Well, my problem is that on my ASP.net site i wrote a function (below) to start the process, but i get an exception
"740" ("the software required privilege elevation")
as if i mark the "AsAdmin" argument of my function to "true", i get that
"UseShellExecute"
can't be true as an exception.

public static int RunProcess(string ApplicationPath, string Parameters = "", bool AsAdmin = false)
{
try
{
global::System.Diagnostics.ProcessStartInfo startInfo = new global::System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = AsAdmin;
if (AsAdmin) { startInfo.Verb = "runas"; }
startInfo.WorkingDirectory = global::System.IO.Path.GetDirectoryName(ApplicationPath);
startInfo.FileName = ApplicationPath;
if (!string.IsNullOrEmpty(Parameters)) { startInfo.Arguments = Parameters; }
startInfo.ErrorDialog = false;
global::System.Diagnostics.Process process = global::System.Diagnostics.Process.Start(startInfo);
process.WaitForExit();
return process.ExitCode;
}
catch (global::System.ComponentModel.Win32Exception ex) { return ex.NativeErrorCode; }
catch { return -1; }
}


What do i do?

Ted Ted
Answer

Have you tried ProcessStartInfo? It allows you to add specific credentials. Check the example below:

ProcessStartInfo myProcess = new ProcessStartInfo(path);
myProcess.UserName = username;
myProcess.Password = MakeSecureString(password);
myProcess.WorkingDirectory = @"C:\Windows\System32";
myProcess.UseShellExecute = false;
// elevate EDIT
myProcess.Verb = "runas";
Process.Start(myProcess);


private static SecureString MakeSecureString(string text)
{
     SecureString secure = new SecureString();
     foreach (char c in text)
     {
         secure.AppendChar(c);
     }
     return secure;
}

Launch a process under another user's credentials