开发者

Registry not being modified with C# application

I have the following snipped of code that is running within a Windows Service.

The service watches the LAN and changes the proxy sett开发者_如何学JAVAings accordingly, the problem is that for some reason the proxy settings are not being updated.

The application is running under the Local System Account but the registry stil ldoes nto change:

Anyone have any ideas?

using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true))
{
    if (key != null)
    {
        key.SetValue("ProxyEnable", Convert.ToInt32(enable), RegistryValueKind.DWord);

        //I/O Flushes
        key.Flush();
        key.Close();
        return;
    }

    //Exception thrown here to test if key is valid.
}


If you are running in the local system account, there is no HKEY_Current_User.

In fact, in many cases, even if you are running a service as a user account, there will be no HKEY_CURRENT_USER, because the service generally won't create a full windows station -- it just uses the user account for authentication, and not the profile.

This is 1 of several reasons that many COM automation-capable applications are not able to be used by services.

You will be able to access HKEY_LOCAL_MACHINE, though.

Edit If you run your service as a specific user account (or if you have the thread in your service impersonate a specific user account), you might be able to use RegOpenCurrentUser function to retrieve a handle to the key you want, and then use RegistryKey.FromHandle to use it from the .Net API's.


First of all, I don't have a clue about registry in C#. These are just guesses.

  1. Did you try F11-stepping through the code? Maybe the flow is not as expected? Is the code even run?

  2. Did SetValue return a value indicating failure?

  3. Does the path possibly have to end in a backslash?

  4. Did Windows redirect the write call to a virtual path? Check by reading the key right after writing and compare to a manual look into the registry.

Update re your comment:

Executing in a console app to check for errors is a very good idea. Since that worked, point 3 can be removed - the rest is still valid. Maybe windows is writing to a virtual path for your server user?

Try running the console app as the service user (also using F11).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜