I have console application, which is working to delete registry value. But when I am trying to do the same in service, it's not working.
The log to txt file is working fine, so I see log every 5 secs. But exception from DeleteValue method says:
Value doesn't exist
Console application (working):
class Program
{
static void Main(string[] args)
{
while (true)
{
KillProxy();
Console.ReadLine();
}
}
private static void KillProxy()
{
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
try
{
key.DeleteValue("AutoConfigURL");
key.Close();
}
catch { }
}
}
}
Service application (not working):
public partial class Service1 : ServiceBase
{
private Timer t1;
/// <summary>
/// Init
/// </summary>
public Service1()
{
InitializeComponent();
}
/// <summary>
/// Service start event
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
t1 = new Timer();
t1.Interval = 5000;
t1.Elapsed += new ElapsedEventHandler(t1_tick);
t1.Enabled = true;
}
/// <summary>
/// Service stop event
/// </summary>
protected override void OnStop()
{
t1.Enabled = false;
}
/// <summary>
/// Timer tick event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void t1_tick(object sender, ElapsedEventArgs e)
{
KillProxy();
}
/// <summary>
/// If key AutoConfigURL exists, delete it
/// </summary>
private void KillProxy()
{
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
try
{
WriteLog("start deleting ");
key.DeleteValue("AutoConfigURL");
key.Close();
}
catch (Exception ex)
{
WriteLog(ex.Message.ToString());
}
}
}
private void WriteLog(string msg)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\logfile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + " " + msg);
sw.Flush();
sw.Close();
}
catch
{
//nothing
}
}
}
The reason for this is that you are accessing the CurrentUser registry subtree which as its name says is specific to the user,
when you run the code in console mode you run it with your user and the content of the CurrentUser registry section retrieved is one, yours, with the keys and sub-keys you know of,
when you run the code as service the default account used to run is Local Service or System and in that context the CurrentUser registry subtree is definitely not yours as the one loaded in console mode.
you should either set the service to run using your own credentials ( you will have to type in username and password ) or keep the app running in console mode, or revisit your application logic, depends on what exactly you need to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With