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
}
}
}