Getting registry values causing program end without exception

I am working on getting and setting registry values in Windows Forms.

My code looks like this:

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SmogUser");
if (((Guid)key.GetValue("DeviceId", Guid.Empty)) == Guid.Empty)
{
    Guid deviceId = Guid.NewGuid();
    key.SetValue("DeviceId", deviceId);
    key.Close();
}
else
{
    Guid deviceId = (Guid)key.GetValue("DeviceId");
}

When I run the program the first time, it enters into the if clause and sets deviceId, but when I run the second time, the program is not continuing and there is no exception.

What is the problem?

Answers


I don't understand well why RegistryKey.GetValue() method behavior is wrong, but I fixed your problem using this code:

        Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SmogUser");
        if (key != null)
        {
            var value = key.GetValue("DeviceId", null) ?? Guid.Empty;

            if (Guid.Empty.Equals(value))
            {
                Guid deviceId = Guid.NewGuid();
                key.SetValue("DeviceId", deviceId);
                key.Close();
            }
            else
            {
                var deviceId = (Guid)key.GetValue("DeviceId");
            }
        }

It seems that if you pass null as default value the method doesn't crash. Then, you can check for null and set Guid variable value to Guid.Empty.


Need Your Help

kohana 3.0.12 get a range of the multiple records

php orm kohana kohana-3.0

I have a kohana 3.0.12 based website and I want to get the first 3 values from the database, then the following 3.

Accordion - Scroll Content within DIV

php html css scroll

I'm using the accordion code from:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.