santra_a
santra_a

Reputation: 85

Get registry value using C#

I am not able to retrieve a software's Installdir. I have tried GetValue and even OpenSubKey but everytime I get a NULL. I am using VS2008, .Net 3.5, 64bit machine, 32bit process setting.

private string GetInstallPath()
{
     string keyValue = string.Empty;
     Object key = Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\My Company\\My Tool", "Installdir", null);
     ...
}

key is returning NULL though there is a valid string there. Equivalent code works in VC++. Please provide your insight to the issue. What am I doing wrong for this supposedly easy task? I cannot use a 'Hive' as it's 4.0 standard. Code level help instead of links would be helpful.

VC++ equivalent

HKEY hkey = NULL;
LSTATUS status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SOFTWARE\\My Company\\My Tool\\", 0, KEY_READ, &hkey );

if ( status == ERROR_SUCCESS )
{
  DWORD type;
  char  buff[ 100 ];
  DWORD numBytes = sizeof( buff );
  if ( RegQueryValueExA( hkey, REGISTRY_ENTRY, NULL, &type, (LPBYTE) buff, &numBytes ) == ERROR_SUCCESS )
 {
 ...
 }

Upvotes: 1

Views: 7079

Answers (1)

Jason
Jason

Reputation: 3960

You mentioned your machine is x64, and your app is 32 bit unless I misread. Given your environment the firs thing I would check is to be sure the key exists in the 64 bit node, HKCU\Software\My Company\... and not in the 32 bit node HKCU\Software\Wow6432Node\My Company\..., if your key exists in the 32 bit node, you will need to make sure your app is a 32 bit app, otherwise, you will need to make sure your app is 64 bit or you won't find the key.

The following code worked for me, running in 64 bit and found the key outside of the Wow6432Node. I don't understand why you can't user 'Hive', it works in both 3.5 and 4.0

RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\VisualStudio\\10.0");

if (regKey != null)
{
    object val = regKey.GetValue("FullScreen");
}

Update: The following also worked for me, running .NET 3.5, if it's not a platform (x86 vs x64) issue, then it is possibly a permissions problem, make sure that the context under which your app is running has access to the registry key (try running the app as administrator or even system)

object test = Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\VisualStudio\\10.0", "FullScreen", null);

Upvotes: 4

Related Questions