Home > Mobile >  How to read a registry after running a reg query in C#
How to read a registry after running a reg query in C#

Time:12-02

I want to identify the port of a device that is connected to my PC, it's a PINPAD, however the only way I could do it was by running the following command in CMD: reg query HKLM\HARDWARE\DEVICEMAP\SERIALCOMM After running this command in CMD "PROMPT COMMAND", it returns the following information: `

HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
    \Device\gertec_usbcdc_AcmSerial0    REG_SZ    COM4

` As you can see, it returns me to COM4 at the end, my question is how to run this command within my application, which library to use and how to assemble this query to obtain the same return within the C# code. Attached is an image of the query performed in CMDimage prompt command, in reg query

I saw some answers here in the forum, and I tried to apply it in my code, but in none I was successful, below are some of the things I tried.


        try
        {
            using (var key = Registry.CurrentUser.OpenSubKey(@"reg query HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM", false)) // False is important!
            {
                var s = key?.GetValue("Version") as string;
                if (!string.IsNullOrWhiteSpace(s))
                {
                    var version = new Version(s);
                }
            }
        }
        catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
        {
            //react appropriately
        }

I also tried

RegistryKey key = Registry.CurrentUser.OpenSubKey(@"HKLM\HARDWARE\DEVICEMAP\SERIALCOMM");

Nesse caso ele sempre retorna a key como null.

CodePudding user response:

Here you can get what you want, you can apply the case there with a little change in the parameters that you will send. Bearing in mind that you only need to run the command as administrator. this link

CodePudding user response:

using Microsoft.Win32;

// Open the subkey of HKLM (i.e., HARDWARE\DEVICEMAP\SERIALCOMM)
var subkey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM");

// Get the value of \Device\gertec_usbcdc_AcmSerial0
var value = subkey.GetValue(@"\Device\gertec_usbcdc_AcmSerial0");

// I print the value "COM4" here, but you can use it however you need
Console.WriteLine(value);

You'll need to handle closing the subkey and such.

  •  Tags:  
  • c#
  • Related