Отказано в доступе при изменении типа запуска службы
Цитата: Владимир от 18.05.2021, 16:02Добрый день. При изменении параметра "Start" по пути "HKLM\SYSTEM\CurrentControlSet\Services\WdiSystemHost" появляется ошибка "Отказано в доступе", программа запущена от администратора. Как можно задать тип запуска этой службе?
Добрый день. При изменении параметра "Start" по пути "HKLM\SYSTEM\CurrentControlSet\Services\WdiSystemHost" появляется ошибка "Отказано в доступе", программа запущена от администратора. Как можно задать тип запуска этой службе?
Цитата: Владимир от 18.05.2021, 23:17Нашел решение:
[spoiler title="Код"]public static class ServiceHelper { [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean ChangeServiceConfig( IntPtr hService, UInt32 nServiceType, UInt32 nStartType, UInt32 nErrorControl, String lpBinaryPathName, String lpLoadOrderGroup, IntPtr lpdwTagId, [In] char[] lpDependencies, String lpServiceStartName, String lpPassword, String lpDisplayName); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern IntPtr OpenService( IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess); [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr OpenSCManager( string machineName, string databaseName, uint dwAccess); [DllImport("advapi32.dll", EntryPoint = "CloseServiceHandle")] public static extern int CloseServiceHandle(IntPtr hSCObject); private const uint SERVICE_NO_CHANGE = 0xFFFFFFFF; private const uint SERVICE_QUERY_CONFIG = 0x00000001; private const uint SERVICE_CHANGE_CONFIG = 0x00000002; private const uint SC_MANAGER_ALL_ACCESS = 0x000F003F; public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode) { var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); if (scManagerHandle == IntPtr.Zero) { throw new ExternalException("Open Service Manager Error"); } var serviceHandle = OpenService( scManagerHandle, svc.ServiceName, SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG); if (serviceHandle == IntPtr.Zero) { throw new ExternalException("Open Service Error"); } var result = ChangeServiceConfig( serviceHandle, SERVICE_NO_CHANGE, (uint)mode, SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, null, null, null); if (result == false) { int nError = Marshal.GetLastWin32Error(); var win32Exception = new Win32Exception(nError); throw new ExternalException("Could not change service start type: " + win32Exception.Message); } CloseServiceHandle(serviceHandle); CloseServiceHandle(scManagerHandle); } }[/spoiler]
Использование:var svc = new ServiceController(WdiSystemHost); ServiceHelper.ChangeStartMode(svc, ServiceStartMode.Disabled);
Нашел решение:
public static class ServiceHelper
{
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern Boolean ChangeServiceConfig(
IntPtr hService,
UInt32 nServiceType,
UInt32 nStartType,
UInt32 nErrorControl,
String lpBinaryPathName,
String lpLoadOrderGroup,
IntPtr lpdwTagId,
[In] char[] lpDependencies,
String lpServiceStartName,
String lpPassword,
String lpDisplayName);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr OpenService(
IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
[DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr OpenSCManager(
string machineName, string databaseName, uint dwAccess);
[DllImport("advapi32.dll", EntryPoint = "CloseServiceHandle")]
public static extern int CloseServiceHandle(IntPtr hSCObject);
private const uint SERVICE_NO_CHANGE = 0xFFFFFFFF;
private const uint SERVICE_QUERY_CONFIG = 0x00000001;
private const uint SERVICE_CHANGE_CONFIG = 0x00000002;
private const uint SC_MANAGER_ALL_ACCESS = 0x000F003F;
public static void ChangeStartMode(ServiceController svc, ServiceStartMode mode)
{
var scManagerHandle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
if (scManagerHandle == IntPtr.Zero)
{
throw new ExternalException("Open Service Manager Error");
}
var serviceHandle = OpenService(
scManagerHandle,
svc.ServiceName,
SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);
if (serviceHandle == IntPtr.Zero)
{
throw new ExternalException("Open Service Error");
}
var result = ChangeServiceConfig(
serviceHandle,
SERVICE_NO_CHANGE,
(uint)mode,
SERVICE_NO_CHANGE,
null,
null,
IntPtr.Zero,
null,
null,
null,
null);
if (result == false)
{
int nError = Marshal.GetLastWin32Error();
var win32Exception = new Win32Exception(nError);
throw new ExternalException("Could not change service start type: "
+ win32Exception.Message);
}
CloseServiceHandle(serviceHandle);
CloseServiceHandle(scManagerHandle);
}
}
Использование:
var svc = new ServiceController(WdiSystemHost); ServiceHelper.ChangeStartMode(svc, ServiceStartMode.Disabled);
Цитата: Станислав от 21.05.2021, 09:34Доброго времени суток! Не хочу создавать лишний топик, поэтому напишу тут.
Христ в ТГ говорит про его курсы С#, где можно их найти?
Заранее спасибо!
Доброго времени суток! Не хочу создавать лишний топик, поэтому напишу тут.
Христ в ТГ говорит про его курсы С#, где можно их найти?
Заранее спасибо!
Цитата: Сергей от 21.05.2021, 09:35Доброе утро ☀️
Уроки C# ➜ https://www.youtube.com/playlist?list=PL05SB3rBbUsraqiEUeS70RKhVAu97nGeb
Доброе утро ☀️
Уроки C# ➜ https://www.youtube.com/playlist?list=PL05SB3rBbUsraqiEUeS70RKhVAu97nGeb
Цитата: ЯR от 21.05.2021, 09:37Здравствуйте.
Внизу страницы есть ссылки на Youtube-канал.
Здравствуйте.
Внизу страницы есть ссылки на Youtube-канал.