Question

This is my method to retrieve the motherboard's UUID relying on the Win32_ComputerSystemProduct struct.

    #region "UUID"
    public static string getUUID()
    {
        string UUID = string.Empty;
        try
        {
            ManagementClass mc = new ManagementClass("Win32_ComputerSystemProduct");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                UUID = mo.Properties["UUID"].Value.ToString();
                break;
            }

            UUID = "";

            if (UUID.Equals(string.Empty)
                || UUID.Equals("")
                || UUID.Equals(null)
                || UUID.Equals("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")
                || UUID.Equals("00000000-0000-0000-0000-000000000000"))
            {
                throw new System.Exception("UUID is invalid.");
            }
            return UUID;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error Message: " + ex.Message);
        }
        return UUID;
    }
    #endregion

I have a built-in exception handler which throws an error in-case the strings are the ones I listed, since C# implicitly doesn't know that a string like FFF...FFF is invalid/error.

I redefined UUID = ""; to test this method, say, in case the user running this script has a blank UUID.

I was wondering -- is this the right way to do it? I am unsure about the return UUID which still returns the UUID even if it's blank, or FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF.

Was it helpful?

Solution

For starters, prior to your if statement, you set the UUID to null.

Next, your if should look like this:

        if (String.IsNullorEmpty(UUID)
            || UUID.Equals("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")
            || UUID.Equals("00000000-0000-0000-0000-000000000000"))
        {
            throw new System.Exception("UUID is invalid.");
        }
        return UUID;

Other then that, this whole if statement should be in the foreach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top