I will check my Windows os name (Windows 8 Pro) in c# but it gives an error, what's wrong?
RegistryKey reg = Registry.LocalMachine.OpenSubKey(#"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion", true);
string currentKey;
currentKey = reg.GetValue("ProductName", true).ToString();
textBox1.Text = currentKey;
You can use Environment.OSVersion for this.
Edit:
Getting the OS name is answered here: Stackoverflow OS Friendly name
I'll just quote MSDN:
Registry.GetValue()-Method
Retrieves the value associated with the specified name, in the specified registry key. If the name is not found in the specified key, returns a default value that you provide, or a null reference (Nothing in Visual Basic) if the specified key does not exist.
This means that the value you are trying to get is not available.
Edit possible Solution:
Source: How to get the “friendly” OS Version Name?
private string GetOSName()
{
var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
select x.GetPropertyValue("Caption")).First();
return name != null ? name.ToString() : "Unknown";
}
And to check whether OS is 32 or 64bit use following code:
private string GetOSBitness()
{
if (Environment.Is64BitOperatingSystem == true)
return " x64";
else
return " x86";
}
Above code will return (at least on my system):
Microsoft Windows 7 Professional x64
You can get the commercial name of your operating system, including service pack information by querying the Windows Management Instrumentation interface:
public static string GetOSNameAndVersion()
{
string str = Environment.OSVersion.ToString();
try
{
var obj2 = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
.Get()
.Cast<System.Management.ManagementObject>()
.First<System.Management.ManagementObject>();
str = ((string)obj2["Caption"]).Trim();
string spMaj = obj2["ServicePackMajorVersion"].ToString();
string spMin = obj2["ServicePackMinorVersion"].ToString();
string osVer = obj2["Version"].ToString();
if (((spMaj != "") && (spMaj != "0")) || ((spMin != "") && (spMin != "0")))
{
str = str + " SP " + spMaj;
if ((spMin != "") && (spMin != "0"))
{
str = str + "." + spMin;
}
}
if (Environment.Is64BitOperatingSystem)
{
str = str + " x64";
}
else
{
str = str + " x86";
}
str = str + " (" + osVer + ")";
}
catch
{
// TODO: Implement your own exception handling here
// the way it is, the method will fall back on to the Environment.OSVersion
// if the query fails
}
if (str.StartsWith("Microsoft"))
{
str = str.Substring("Microsoft".Length + 1);
}
return str;
}
Hacking at the registry is probably the wrong solution.
But why is it failing? Since you use Registry.LocalMachine, the HKLM is wrong. Remove the HKLM. That's a clear error.
On top of that watch out for registry redirection. Perhaps your process is 32 bit but the value you are looking for is in the 64 bit view of the registry. Use the RegistryView enumeration to gain access to the 64 bit view.
Your program is subject to what I presume to be a NullReferenceException because the program cannot find the registry sub-key because the path that you have supplied is incorrect.
You do not need to specify the hive in the hive path because your relative path is already the local hive. Exclude the hive from the path like like this:
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", true);
Depending on your programs' access privileges and operating system configuration your program may still throw an exception due to your program having insufficient access permissions.
Related
I am trying to save the path of an application to a variable by using the registry.
What i want to achieve is:
1) Check if this application has an entry in the registry? (if it was installed or not)
2) If yes, I want to save the path to a variable which I can use later to use a program which is located in this path
So far i got
public void Run1()
{
Console.WriteLine("Reading OCR path from registry");
string keyName = #"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Tomcat\Common";
string valueName = "OCR_path";
string OCRPath = Microsoft.Win32.Registry.GetValue(keyName, valueName, null) as string;
if (string.IsNullOrWhiteSpace(OCRPath))
{
string text = "3";
System.IO.File.WriteAllText(#"C:\Users\Public\TestFolder\OCR-Toolkit-Check.txt", text);
}
}
Console.WriteLine("Reading OCR path from Registry:");
string keyName = #"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Tomcat\Common";
string valueName = "OCR_path";
if (Microsoft.Win32.Registry.GetValue(keyName, valueName, null) != null)
{
object variable = Microsoft.Win32.Registry.GetValue(keyName, valueName, null);
}
You might want to do the null-check, after reading it to a variable. Besides, you can cast the object variable to string afterwards.
I used a different approach and it works now. The path is saved into the variable OCRPath
public void Run1()
{
Console.WriteLine("Reading OCR path from registry");
string keyName = #"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Tomcat\Common";
string valueName = "OCR_path";
string OCRPath = Microsoft.Win32.Registry.GetValue(keyName, valueName, null) as string;
if (string.IsNullOrWhiteSpace(OCRPath))
{
string text = "3";
System.IO.File.WriteAllText(#"C:\Users\Public\TestFolder\OCR-Toolkit-Check.txt", text);
}
}
Holy moly, do not hardcode "Wow6432Node". You can get away with that on a 64 bit system opening the registry in 64-bit mode, but if you open the registry in 32-bit mode it will create a horrid thing you don't want to see. Also if you have a 32-bit OS, there is not supposed to be a "Wow6432Node" folder so you will end up creating stuff in places you shouldn't.
If you don't require opening the registry using only privileges and can rely on the permissions of the user to create/open/read keys then Microsoft already has Microsoft.Win32.Registry to help you.
string sPath = null;
RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey appKey = hklm.OpenSubKey(#"SOFTWARE\Tomcat\Common");
if(appKey != null)
{
object oPath = appKey.GetValue("OCR_path", null);
if(oPath != null && oPath is string)
{
sPath = oPath.ToString();
}
}
My Application is running on a Windows Server via RDP. In the Application I want to know if the Client (with the RDP-Session) is a Mobile Device.
Is it possible to get the Client Operating System?
For a list of all RDP environment variables of the current user connecting please see the below comment.
The reg location for citrix ICA connections is HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\Ica\Session\\Connection\
The Subkeys ClientProductID and ClientType will give reference to what kind of device is connecting.
Here is some basic code to get Remote Session and then get the sessions information from regedit.
// Prints out ICA or RDP session ID of current user & gets ICA session ClientType variable
using System;
using Microsoft.Win32;
namespace ViaRegedit
{
class Program03
{
static void Main(string[] args)
{
// Obtain an instance of RegistryKey for the CurrentUser registry
RegistryKey rkCurrentUser = Registry.CurrentUser;
// Obtain the test key (read-only) and display it.
RegistryKey rkTest = rkCurrentUser.OpenSubKey("Remote");
foreach (string valueName in rkTest.GetSubKeyNames())
{
//Getting path to RDP/Citrix session ID
string RDPICApath = "";
if (rkTest.OpenSubKey(valueName) != null && rkTest.OpenSubKey(valueName) != null) { RDPICApath = rkTest.OpenSubKey(valueName).ToString(); }
Console.WriteLine("Getting CurrentUser ICA-RDP path from string = " + RDPICApath);
//List<string> RDPICAnumber = RDPICApath.Split('\\').ToList();
string RDPICAnumber = RDPICApath.Substring(RDPICApath.LastIndexOf('\\') + 1);
Console.WriteLine("Current User RDPICAnumber = " + RDPICAnumber);
//Getting reg local machine info for Citrix based on RDP/Citrix session ID "RDPICAnumber"
string regLocal = #"SOFTWARE\Citrix\Ica\Session\" + RDPICAnumber + #"\Connection";
RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey citrixKey = localKey.OpenSubKey(regLocal);
Console.WriteLine("Registry " + citrixKey + " Does Exist - going to get ClientType");
//getting clietAddress var from citrixKey
string clientType = "";
if (citrixKey != null && citrixKey.GetValue("clientType") != null)
{clientType = citrixKey.GetValue("ClientType").ToString();}
Console.WriteLine("Getting current user clientType from string = " + clientType);
}
rkTest.Close();
rkCurrentUser.Close();
Console.ReadLine();
}
}
}
You could easily replace clientType with ClientProductID and use the following reference getting ClientProductID information.
I am facing this same problem. I tried reading the WTSClientProductId value from the WTSQuerySessionInformation Win32 API function, but it always returns 0x0001, even when called from a session started from an Android tablet.
I'm trying to read the registry key "RPSessionInterval" from the subkey "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" in C#. I'm using the following code and getting the exception "Object reference not set to an instance of an object."
string systemRestore = #"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore";
RegistryKey baseRegistryKey = Registry.LocalMachine;
public string SystemRestoreStatus(string subKey, string keyName)
{
RegistryKey rkSubKey = baseRegistryKey.OpenSubKey(systemRestore);
if (rkSubKey != null)
{
try
{
string sysRestore = rkSubKey.GetValue("RPSessionInterval").ToString();
if (string.Compare(sysRestore, "1") == 0)
{
MessageBox.Show("System Restore is Enabled!");
return "System Restore is Enabled!";
}
else if (string.Compare(sysRestore, "0") == 0)
{
MessageBox.Show("System Restore is Disabled!");
return "System Restore is Disabled!";
}
else
{
return null;
}
}
catch (Exception ex) //This exception is thrown
{
MessageBox.Show("Error while reading registry key: " + subKey + "\\" + keyName + ". ErrorMessage: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
else
{
MessageBox.Show("Error while reading registry key: " + subKey + "\\" + keyName + " does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
Here is a picture showing that the registry key actually exists:
You most likely have a spelling issue for the call to SystemRestoreStatus, which is causing the exception on the following line:
string sysRestore = rkSubKey.GetValue(keyName).ToString();
If you aren't sure whether the value will exist or not, you can change this line to:
string sysRestore = rkSubKey.GetValue(keyName) as string;
and then test to see if the string is null or empty before trying to use it.
Update
Another possibility is that you are executing the code from a 32-bit application on a 64-bit OS. In this case, .Net helpfully redirects your request to the
SOFTWARE\Wow6432Node\Microsoft\...
node instead.
You can get around this issue by using RegistryKey.OpenBaseKey using RegistryView.Registry64 as the second parameter.
You probably have the wrong bitness for your C# application. By default, a Visual Studio 2010 C# project will compile to x86 (32-bit). A 32-bit application running on a 64-bit OS can generally only access the 32-bit registry, the contents of which are often different than the native 64-bit registry. Change the architecture to "Any CPU" or "x64" and it may work.
I need to get a list of installed program on local machine with application icons. Below is the code snippet that am using to get the list of installed program and installed directory path.
/// <summary>
/// Gets a list of installed software and, if known, the software's install path.
/// </summary>
/// <returns></returns>
private string Getinstalledsoftware()
{
//Declare the string to hold the list:
string Software = null;
//The registry key:
string SoftwareKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
{
//Let's go through the registry keys and get the info we need:
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
//If the key has value, continue, if not, skip it:
if (!(sk.GetValue("DisplayName") == null))
{
//Is the install location known?
if (sk.GetValue("InstallLocation") == null)
Software += sk.GetValue("DisplayName") + " - Install path not known\n"; //Nope, not here.
else
Software += sk.GetValue("DisplayName") + " - " + sk.GetValue("InstallLocation") + "\n"; //Yes, here it is...
}
}
catch (Exception ex)
{
//No, that exception is not getting away... :P
}
}
}
}
return Software;
}
Now the issue is how i can get the installed application icon ?
Thanks in advance.
To determine if its an update, there will be a key called IsMinorUpgrade. This is present and set to a 1 for updates. If it's 0 or not present, then it's not an update.
To get an icon from an executable, use this code:
VB:
Public Function IconFromFilePath(filePath As String) As Icon
Dim result As Icon = Nothing
Try
result = Icon.ExtractAssociatedIcon(filePath)
Catch ''# swallow and return nothing. You could supply a default Icon here as well
End Try
Return result
End Function
C#:
public Icon IconFromFilePath(string filePath)
{
Icon result = null;
try {
result = Icon.ExtractAssociatedIcon(filePath);
} catch { }
return result;
}
To extract icon of installed windows application first we need to figure out the location of icon for the installed windows application. This information is stored in registry at following locations -
Key name - HEKY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
Value - DisplayIcon
Key name - HKEY_CLASSES_ROOT\Installer\Products{productID}
Value - ProductIcon
For more detail and code to get application icons -
http://newapputil.blogspot.in/2015/06/extract-icons-of-installed-windows_17.html
How can I get the location of the tnsnames.ora file by code, in a machine with the Oracle client installed?
Is there a windows registry key indicating the location of this file?
Some years ago I had the same problem.
Back then I had to support Oracle 9 and 10 so the code only takes care of those versions, but maybe it saves you from some research.
The idea is to:
search the registry to determine the oracle client version
try to find the ORACLE_HOME
finally get the tnsnames from HOME
public enum OracleVersion
{
Oracle9,
Oracle10,
Oracle0
};
private OracleVersion GetOracleVersion()
{
RegistryKey rgkLM = Registry.LocalMachine;
RegistryKey rgkAllHome = rgkLM.OpenSubKey(#"SOFTWARE\ORACLE\ALL_HOMES");
/*
* 10g Installationen don't have an ALL_HOMES key
* Try to find HOME at SOFTWARE\ORACLE\
* 10g homes start with KEY_
*/
string[] okeys = rgkLM.OpenSubKey(#"SOFTWARE\ORACLE").GetSubKeyNames();
foreach (string okey in okeys)
{
if (okey.StartsWith("KEY_"))
return OracleVersion.Oracle10;
}
if (rgkAllHome != null)
{
string strLastHome = "";
object objLastHome = rgkAllHome.GetValue("LAST_HOME");
strLastHome = objLastHome.ToString();
RegistryKey rgkActualHome = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\ORACLE\HOME" + strLastHome);
string strOraHome = "";
object objOraHome = rgkActualHome.GetValue("ORACLE_HOME");
string strOracleHome = strOraHome = objOraHome.ToString();
return OracleVersion.Oracle9;
}
return OracleVersion.Oracle0;
}
private string GetOracleHome()
{
RegistryKey rgkLM = Registry.LocalMachine;
RegistryKey rgkAllHome = rgkLM.OpenSubKey(#"SOFTWARE\ORACLE\ALL_HOMES");
OracleVersion ov = this.GetOracleVersion();
switch(ov)
{
case OracleVersion.Oracle10:
{
string[] okeys = rgkLM.OpenSubKey(#"SOFTWARE\ORACLE").GetSubKeyNames();
foreach (string okey in okeys)
{
if (okey.StartsWith("KEY_"))
{
return rgkLM.OpenSubKey(#"SOFTWARE\ORACLE\" + okey).GetValue("ORACLE_HOME") as string;
}
}
throw new Exception("No Oracle Home found");
}
case OracleVersion.Oracle9:
{
string strLastHome = "";
object objLastHome = rgkAllHome.GetValue("LAST_HOME");
strLastHome = objLastHome.ToString();
RegistryKey rgkActualHome = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\ORACLE\HOME" + strLastHome);
string strOraHome = "";
object objOraHome = rgkActualHome.GetValue("ORACLE_HOME");
string strOracleHome = strOraHome = objOraHome.ToString();
return strOraHome;
}
default:
{
throw new Exception("No supported Oracle Installation found");
}
}
}
public string GetTNSNAMESORAFilePath()
{
string strOracleHome = GetOracleHome();
if (strOracleHome != "")
{
string strTNSNAMESORAFilePath = strOracleHome + #"\NETWORK\ADMIN\TNSNAMES.ORA";
if (File.Exists(strTNSNAMESORAFilePath))
{
return strTNSNAMESORAFilePath;
}
else
{
strTNSNAMESORAFilePath = strOracleHome + #"\NET80\ADMIN\TNSNAMES.ORA";
if (File.Exists(strTNSNAMESORAFilePath))
{
return strTNSNAMESORAFilePath;
}
else
{
throw new SystemException("Could not find tnsnames.ora");
}
}
}
else
{
throw new SystemException("Could not determine ORAHOME");
}
}
On Windows, the most likely locations are either %ORACLE_HOME%/network/admin or %TNS_ADMIN% (or the TNS_ADMIN registry setting). These two cover almost every installation.
Of course it is possible to have a working Oracle client without this file. Oracle has bewildering array of networking options, and there are plenty of ways to achieve a working setup with using TNSNAMES. Depending on what you are trying to achieve here, your first port of call might be the sqlnet.ora file, which is also found in %ORACLE_HOME%/network/admin. This should contain a line that looks something like this:
NAMES.DIRECTORY_PATH= (LDAP, TNSNAMES, HOSTNAME)
TNSNAMES means it will use the TNSNAMES.ora file (second in this case). LDAP and HOSTNAME are alternate ways of resolving the database. If there is no TNSNAMES the TNSNAMES.ora file will be ignored if it exists in the right place.
In C# / .NET this should get you the environment variables:
Environment.GetEnvironmentVariable("ORACLE_HOME");
Environment.GetEnvironmentVariable("TNS_ADMIN");
List<string> logicalDrives = Directory.GetLogicalDrives().ToList();
List<string> result = new List<string>();
foreach (string drive in logicalDrives)
{
Console.WriteLine("Searching " + drive);
DriveInfo di = new DriveInfo(drive);
if(di.IsReady)
result = Directory.GetFiles(drive, "tnsnames.ora", SearchOption.AllDirectories).ToList();
if (0 < result.Count) return;
}
foreach (string file in result) { Console.WriteLine(result); }
According to the net that depends on the version of Oracle and the working directory of the SQL*Plus process. This first link tells you the environment variable that specifies the base path for some versions (7, 8, 9i) of Oracle. If you use a different one, I'm sure there's a similar way to get to the system directory.
If you spread versions of these files all over the place though and rely on the "look for a local tnsnames.ora first" behaviour of the client, then I guess you're out of luck.
I'm not a C# or a Windows guy for that matter so hopefully this helps. The tnsnames.ora file should be located in:
ORACLE_HOME\network\admin
If an alternate location has been specified, it should be available via the TNS_ADMIN registry key.
See this link for more information on how Oracle handles tns names on Windows.