I cant change registry value - c#

I am trying to write an application to be able to change a few registry values.Such as Dns Server,Defalut Gateway .I am using this code below for doing this
RegistryKey openSubKey = Registry.LocalMachine.OpenSubKey(path, true);
if (openSubKey != null)
{
//HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\Tcpip\Parameters\Interfaces\{F7DFBC05-B946-4C27-A58B-13BFB3FCC04E}
openSubKey.SetValue("IPAddress", "192.168.2.132");
openSubKey.SetValue("SubnetMask", "255.255.255.0");
openSubKey.SetValue("DefaultGateway", "192.168.2.2");
openSubKey.SetValue("NameServer", ""192.168.2.132,192.168.2.132"");
.Actually code works .I can see the new values in th registry as you can see
However when I check network connections I have realized that nothing changed
but NameServer.What am I doing wrong here.

My suggestion is instead of direct registry manipulation, use WMI. See this StackOverflow post or this Code Project article on using WMI to update the Network Configuration.
Mostly you will have to work with Win32_NetworkAdapterConfiguration WMI object.

Related

Editing Local_Machine RegistryKeys Programmatically (C#)

I'm trying to make a program that changes the registry key values on remote machines to block/allow users from personalizing their lock-screen images. It seems the key I need to create is at HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Personalizationwith a name of NoChangingLockScreen.
I could easily do this with a .reg file and merge any changes into their registry (I planned on creating a windows service to monitor for changes in the file), although it seems I cannot even modify any keys inside the HKEY_LOCAL_MACHINE class.
Please note:
I am a domain admin across our network, and all remote computers have admin rights
This issue does not just occur when modifying a remote PC's keys, but my own as well
I've created the RegistryKey object as writable (See below code)
It seems I cannot even use the OpenSubKey method, as reading the local_machine path just throws an object exception
I've checked the permissions inside the Registry for that specific class and made sure my account had full control
I have found very little documentation on other people having permissions issues
RegistryKey myKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Policies\Microsoft\Windows", true);
Registry.ClassesRoot is for HKEY_CLASSES_ROOT. You need to use Registry.LocalMachine field like this:
using (var registryKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Policies\Microsoft\Windows", writable: true))
{
...
}
Also note, that this is for local registry access. If you wish to open remote registry, you need to use another method:
using (var remoteBaseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "RemoteMachineName"))
using (var registryKey = remoteBaseKey.OpenSubKey(#"SOFTWARE\Policies\Microsoft\Windows", writable: true))
{
...
}

Windows-7:Disable internet connection sharing on network adapter when it's in hidden state?

I'm trying to share internet over a network adapter on windows-7 using NetConLib.dll.
In order to do this, internet sharing should be disabled on all other network adapters.
In normal cases. I can iterate all the installed network adapters and disable sharing on them.
However, sometimes when the network device is unplugged, the adapter is hidden in windows.
But it's properties is still present inside windows registry.
I can't even find the adapter in Control Panel.
And off course, can't iterate it using the NetConlib library.
Possible scenarios.
The easiest way, would be using a windows command to disable internet
sharing on all the adapters. Regardless of their visibility.
Is that possible in anyway ?
The second solution is to recover the network adapter from hidden state, so that
NetConlib could iterate through it and disable it.
I tried to find the adapter's properties in windows registry and unhide it, But couldn't find anything.
Any solution?
#erm3nda.
Thank you for the informative answer. Although it didn't fix the problem I'm facing with NetConlib.
SC config correctly shuts down ICS service. But the shared network adapter continues on being flagged as Shared1. So ICS service being turned off doesn't seem to affect the adapters' settings.
Quite interestingly; when you try to share another adapter using windows GUI (Right click on adapter -> Properties -> Share), a message is prompted telling you
"there is another adapter being shared currently, your new adapter
will be shared instead". You click ok and it's done.
I've been digging the entire internet the whole afternoon to see if there are other solutions using CMD commands.
Maybe there could be a away to share an adapter with a command. This way windows would handle disabling other adapters. In a similar way as when the GUI is used.
1: Windows tells you which adapter is currently being shared in Control Panel\Network and Internet\Network Connections).
Possible solution 1: Disable ICS at all.
You can stop ICS service, so none of the connections will be at sharing status and will not conflict with NetConLib.dll. (Not sure about the hidden ones, you must try).
You can manage it from command line using:
net start SharedAccess or net stop SharedAccess
Also, if you need to disable it from reboot to, must disable service using:
sc config SharedAccess start= disabled
Notes and references:
Executing sc config will display "start= OPTIONS" and some other.
The space below = and option is mandatory. You can check result
running services.msc from Run or cmd.
Exec net to display OPTIONS. The name of service is on the
services.msc list under "Name of the service" label from ICS service.
netsh routing is not on Win7 anymore, so you only can
start/stop/enable/disable but not enable for a particular Interface.
You must set by handMouse... This not work under Win7 ICS into XP
system
Sc Config command was from this cool documentation i found
today.
Possible solution 2: Remove ghost interfaces?
I try also around Adapters and interfaces into registry and do not see anything about show/hid/ghost/enabled or similar. I also search here kb 314053 for registry conf.
I can suggeest try Possible solution 1 :) or directly delete hidden/ghost adapters.
You can do it by two ways. Devcon remove option will delete also drivers.
Device manager: Run set devmgr_show_nonpresent_devices=1 and run
devmgmt.msc. You must see over "See" a "Show hidden" option. The
show_nonpresent must reveal also hidden devices, not only inactive.
kb 269155 - You must click over #link named "Let me fix it
myself"
With devcon.exe utility: This is a device manager tool from Windows
with power moves. You will find a very big and helpfull guide
here.
Basic usage for find netcards devcon findall =net, also you can devcon findall =net *ndis* to list all ndis cards.
Basic usage for remove will be devcon remove =net *ndis* to remove all ndis card type.
I try also enable/disable commands but nothing has change into my network interfaces list.
I removed my own wifi card to test it :) Anyway, i didn't notice any option about "Unhide" feature for such devices from conections panel.
NEW EDIT (Too much verbose, right?)
I found a tool called ics-manager from this superuser post. - read answer #3
You can download directly from utapyngo's Git project page.
It's based on .Net Framework 4. Yo must download and run the build.bat to compile both exe's (You got also the C# source). The solution is to get only the compiled IcsManager.exe (command line version) with the only needed library IcsManagerLibrary.dll.
This app is using also NETCONLib.dll, so you can use it, or read the source to see wich is the correct function you need to do it and implement on your development.
If you got problems with the Ip range "192.168.137.1", you can set from Registry permanently, or run netsh interface ipv4 set address name="YOUR-INTERFACE" source=static addr=192.168.2.1 mask=255.255.255.0. You will got ugly errors from launch the netsh interface using tilde or accutes into interfaces name (Spanish default ethernet name is "Conexión de áreal local"... a joke).
Note: You can pack all at once, using first a Bat to call the IcsManager.exe' with the arguments needed, then launch the netsh configure command later from same batch to full configure.
Comment: About the prompt when try to overwrite an shared connection, it's surely because only one could be shared. I also see, they are configured as Public and Home to set the pair, but i can't find where's the registry key...Also make some exports from reg and using Diffs, no lucky. I got stuck at diffs and start to search "ICS C++ and C#" on Google, then found it.
Extra: I got the netsh it into a bat, and it's launched for Windows Task when a Ethernet cable is plugged (Here is the howto) in order to use with Android Reverse Tethering. As you can see, im too interesting into your question because it makes me research better and also learned a lot.
Sorry about my bad English. Im not.
Regards.
I found that by going into Device Manager, you can show the Hidden Devices and try to disable the internet sharing on the adapters.
Hopefully this is near what you are asking. Good luck!
Atm
Source: http://msdn.microsoft.com/en-us/library/windows/hardware/ff553955%28v=vs.85%29.aspx
I'm about 10 years late to the party, but the complete solution to this problem is nowhere else on the internet. In order to disable internet connection sharing for a device that is unplugged or uninstalled you will need to:
Clear the shared access registry
Clear the WMI sharing entry for the device
Disable sharing through the netcon library
Clearing the registry:
You need to set two registry keys to 0xFFFFFFFF:
HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess\PrivateIndex and
HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess\PublicIndex
For example in powershell:
Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess" -Name "PrivateIndex" -Value 0xFFFFFFFF
Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\SharedAccess" -Name "PublicIndex" -Value 0xFFFFFFFF
Clear the WMI sharing entry for the device:
For every HNet_ConnectionProperties you must ensure IsIcsPublic and IsIcsPrivate is set to false. You can view which interface has IsIcsPublic or IsIcsPrivate set in powershell:
Get-CimInstance -ClassName 'HNet_ConnectionProperties' -Namespace 'root\Microsoft\HomeNet' | Format-Table
Unfortunately, the Set-CimInstance cmdlet does not appear to work in this scenario, so we have to choose another language. Fortunately, code to set these values to false can be found online. For example, here is some C# that performs this task (attibuted to utapyngo)
public static void CleanupWMISharingEntries()
{
var scope = new ManagementScope("root\\Microsoft\\HomeNet");
scope.Connect();
var options = new PutOptions();
options.Type = PutType.UpdateOnly;
var query = new ObjectQuery("SELECT * FROM HNet_ConnectionProperties");
var srchr = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject entry in srchr.Get())
{
if ((bool)entry["IsIcsPrivate"])
entry["IsIcsPrivate"] = false;
if ((bool)entry["IsIcsPublic"])
entry["IsIcsPublic"] = false;
entry.Put(options);
}
}
... and some vbscript (attributed to billchaison):
set WMI = GetObject("WinMgmts:\root\Microsoft\HomeNet")
set objs1 = WMI.ExecQuery("SELECT * FROM HNet_ConnectionProperties WHERE IsIcsPrivate = TRUE")
for each obj in objs1
obj.IsIcsPrivate = FALSE
obj.Put_
next
set objs2 = WMI.ExecQuery("SELECT * FROM HNet_ConnectionProperties WHERE IsIcsPublic = TRUE")
for each obj in objs2
obj.IsIcsPublic = FALSE
obj.Put_
next
Disable sharing through the netcon library:
This part you probably already know, but for completeness, here is some powershell that does it:
regsvr32.exe /s hnetcfg.dll
$NetShare = New-Object -ComObject HNetCfg.HNetShare
foreach ($RawConnection in $NetShare.EnumEveryConnection) {
$Sharing = $NetShare.INetSharingConfigurationForINetConnection.Invoke($RawConnection)
$Sharing.DisableSharing()
}
The documentation for the relevant COM APIs for netcon can be found on MSDN

How to set TerminalServiceProfile Path in Windows server 2003 Active Directory using C#?

I know in Windows 2008 AD, we have msTsProfilePath AD attribute using which we can directly set the terminal service profile path.
But we have windows 2003 AD and i need to set terminal service profile path using C#.
I came across following article and have come to know from some other articles that terminal service profile path gets stored in userParameters property.
http://www.selfadsi.org/user-attributes-w2k3.htm#List
Can somebody tell me how to set CtxWFProfilePath in userParameters through C# ?
Thanks,
Nikhil.
Update: Please refer to this MSDN forum where this gentleman "Konrad Neitzel" directed me to some useful links. But as mentioned in the thread, i am finding difficulties in using WTSSetUserConfig method. Any idea ?
I battled with this one too but finally was able to put together a working solution from dozens of different sites. I'm not sure is this exactly what you are needing but hopefully it helps
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "name", "container");
UserPrincipals user = UserPrincipals.FindByIdentity(domainContext, "ad_user_name");
DirectoryEntry dirEntry = (user.GetUnderlyingObject() as DirectoryEntry);
dirEntry.InvokeSet("TerminalServicesProfilePath", "yourpath");
dirEntry.CommitChanges();
You can find all the attributes from this site (another tough thign to find out)
http://www.virtualizationadmin.com/articles-tutorials/terminal-services/scripting/scripting-server-based-computing-terminal-services-attributes-active-directory-user-objects.html

Read Event Log Remotely with .NET

I want to read the Event Log on a remote computer to check for errors during testing. Here's some relevant code:
public bool CheckEventLogs(DateTime start)
{
EventLog myEventLog = new EventLog("CustomLog", "ServerName");
bool errorFound = false;
foreach (EventLogEntry entry in myEventLog.Entries)
{
if (entry.EntryType == EventLogEntryType.Error && entry.TimeGenerated >= start)
{
Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
errorFound = true;
}
}
return errorFound;
}
Currently, this code throws an exception (Attempted to perform an unauthorized operation). According to MSDN, I need EventLogPermission, but I have been struggling to find any examples of how to use this permission. Does anyone have an example of how to do this?
Edit: Response to Comments
Thank you all for the comments - here is the additional information requested:
The exception is thrown from the foreach statement. Specifically, when stepping through the code it thrown in the step after when in is highlighted. It seems that I was able to create the event log object but I'm not able to access the entries in the event log.
My account does not have permission to read the event log on the target system, but I have credentials for an account which does. When connecting manually through the event viewer there is an option to connect as another user. After doing this manually, then my code ran without a problem. However, I cannot rely doing it manually every time this program runs. What I need is a way to connect as another user programmaticly. I thought that the EventLogPermission would be the way to do that, but maybe there is another way. If anyone knows how to connect to a remote log as a different user in C#, that would be exactly what I was looking for.
WMI is incredibly useful for this, a snippet like
SELECT Logfile,TimeGenerated,Type,SourceName,Message FROM Win32_NTLogEvent
Would allow you to query the logs. This utility from MS will allow you to explore WMI and will even build the .net code to invoke the queries.
Another benefit to this is that its going to get all the events and bring them local to the application where you can parse them at your leisure. Iterating the events in the way you are doing now is prone to failure if the connection is broken while you are processing (incidentally this is the same method that is typically employed with database access).
Thanks to everyone who provided comments on this question. Once I realized that the permissions might not be a part of .NET but part of Windows and the Event Viewer itself, I had some new direction for my own investigations.
It looks like a "net use" command was all that was needed to establish the connection between my local computer and the remote computer. When calling "net use" before using the code I posted in the question, things worked beautifully. It is simple enough to call that from the code before reading from the event log.
Thanks again for your help!

Getting back "ResolveIOD" while trying to open HKLM\Software\Microsoft\Windows\CurrentVersion\Installer\ on Windows 7?

I'm trying to get at the UserData registry subkeys on a C# 3.5 application so I can look up the installed location of an external program to start it.
Doing something like this:
RegistryKey installerKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Installer");
and then
RegistryKey userDataKey = installerKey.OpenSubKey("UserData");
returns null; if I go back and call installerKey.GetSubKeyNames() to figure out which subkey names are present under Installer it only returns one subkey name: ResolveIOD. I haven't been able to find what only being able to find this key indicates.
regedit does not show the ResolveIOD key being there, and it shows that much more than just that one key is present - UserData, Folders, Secure, etc are all there and not returned by GetSubKeyNames() either.
This is my first time accessing anything in the Installer section of the registry hive, so I've probably done something wrong. Is there some kind of special permission I have to request in order to read these (probably sensitive, security-wise) keys from a client application, or is this generally not an acceptable thing to do on Windows 7 and I should find an alternative way of figuring out where the program is located?
Because I'm seeing this mentioned on other registry questions: This is running as a 32-bit application on 64-bit Windows.
First, to ensure you are accessing the 64-bit registry rather than the Wow6432Node sandbox, use the RegOpenKeyEx function with KEY_WOW64_64KEY (http://msdn.microsoft.com/en-us/library/ms724878%28v=vs.85%29.aspx) included as one of the access options.
pinvoke.net has a C# example: http://www.pinvoke.net/default.aspx/advapi32/RegOpenKeyEx.html
Also note that with UAC enabled, an unelevated app will, at best, only have read access to HKLM.

Categories

Resources