C# code- How to set Windows Service as auto start service

public bool setAutoStartService(string ServiceName, bool auto)
{
try
{
string subKey = "SYSTEM\\CurrentControlSet\\Services\\" + ServiceName;
// Setting
RegistryKey rk = baseRegistryKey;
// I have to use CreateSubKey
// (create or open it if already exits),
// 'cause OpenSubKey open a subKey as read-only
RegistryKey sk1 = rk.CreateSubKey(subKey);
// Save the value
if (auto)
{
//System.Windows.Forms.MessageBox.Show(sk1.GetValue("Start").ToString());
sk1.SetValue("Start", (int)2);
}
else
{
sk1.SetValue("Start", (int)3);
}

return true;
}
catch (Exception e)
{
logger.Error("setAutoStartService : " + e.Message);
logger.Debug(e.StackTrace);
// error!
//ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
return false;
}
}

0 comments: