Reputation: 49
Programmatically stopping a windows service in c# generates below listed System.InvalidOperationException
{Access is denied}
If i start/stop through windows interface then everything works fine! I'm an Admin user and running the service under Windows 7
Upvotes: 0
Views: 1241
Reputation: 678
If authentication is the problem ...
You can programatically control the user from which you're doing stuff with, using
WindowsIdentity
and
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(...)
I don't know if that would work, but it could be worth a shot.
IntPtr token IntPtr.Zero;
LogonUser(username, password ..., ref token) //and some other parameters
var identity = WindowsIdentity(token);
using(identity.Impersonate())
{
//do stuff here using another identity
//find service and stop it
}
edit: This can be used for authentication on remote servers.
Upvotes: 0
Reputation: 60694
I'm not sure how you are trying to stop it, but I tried this on my system now, and this approach at least works fine:
var p = Process.Start(new ProcessStartInfo
{
FileName = "net",
Arguments = "stop NameOfService",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
});
p.WaitForExit(); //add this line if you want to make sure that the service is stopped before your program execution continues
Upvotes: 1
Reputation: 60190
This sounds like a UAC issue - try running the application which shall control the service as admin (right-click, "Run as Administrator").
Note that even an administrator account does not have full privileges unless you explicitly run applications in administrator mode - this was introduced for protecting the user from malicious software in Windows Vista and has been there since then.
Upvotes: 0