Reputation: 1428
I am wanting to write directly to the registry using Microsoft.Win32.Registry
. I can do this is a reg file like so:
swreg = File.AppendText(strRegPath); //Opens the file:
swreg.WriteLine(@"[HKEY_CURRENT_USER\Software\Microsoft\Office\Outlook\OMI Account Manager\Accounts\[email protected]");
swreg.WriteLine("\"DCEmail\"=dword:00000002");
swreg.WriteLine("\"POP3 Server\"=\"10.0.0.200\"");
swreg.WriteLine("\"POP3 Port\"=dword:0000006e");
This creates a reg file, and I can execute the file which create the reg keys. I have tried to something similar using Microsoft.Win32.Registry
like so:
var RKOutlook = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Outlook\OMI Account Manager\Accounts");
if (RKOutlook.OpenSubKey("[email protected]") == null)
{
RKOutlook.CreateSubKey("[email protected]");
RKOutlook = RKOutlook.OpenSubKey("[email protected]", true);
}
However I receive an System.NullReferenceException was unhandled
error. How can I achieve writing directly to the registry without using a reg file?
Upvotes: 2
Views: 3719
Reputation: 70766
Registry.CurrentUser.OpenSubKey will return null
if the operation fails, you then assign this value to RKOutlook
and attempt to access .OpenSubKey
(Probably why you get the exception).
You should also check that the object is not null
before attempting to access the OpenSubKey
method:
if (RKOutlook != null && RKOutlook.OpenSubKey([email protected]) == null)
{
RKOutlook.CreateSubKey([email protected]);
RKOutlook = RKOutlook.OpenSubKey([email protected], true);
}
Upvotes: 1
Reputation: 159
Reading from and writing to Registry
This code is in VB.NET but that can be translated to C# The following code shows how to read a string from HKEY_CURRENT_USER.
Microsoft.Win32.RegistryKey regVersion = null;
dynamic keyValue = "Software\\Microsoft\\TestApp\\1.0";
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyValue, false);
int intVersion = 0;
if (regVersion != null) {
intVersion = regVersion.GetValue("Version", 0);
regVersion.Close();
}
The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.
var regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", true);
if (regVersion == null) {
// Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0");
}
int intVersion = 0;
if (regVersion != null) {
intVersion = regVersion.GetValue("Version", 0);
intVersion = intVersion + 1;
regVersion.SetValue("Version", intVersion);
regVersion.Close();
}
Upvotes: 1