I'm trying to work with STATIC properties in C#. I have some properties I
get from the registry, so I don't want to instance the class.
I have something like this, but I cannot get it to work. Whenever I try to
access these properties from other classes or project in the same solution
(referenced, of course), I cannot find them...
Would anybody be so kind to give me a hand?
Thanks a lot!!!
----
namespace MyLibrary
{
public static class Config
{
private RegistryKey regMySoft =
Registry.LocalMachine.OpenSubKey("SOFTWARE\\MySoft");
public static String MailServer
{
get
{
return regSoft.GetValue("mailServer").ToString();
}
set
{
regSoft.SetValue("mailServer", value);
}
}
}
}
Morten Wennevik [C# MVP] - 09 Jun 2007 11:28 GMT
> I'm trying to work with STATIC properties in C#. I have some properties I
> get from the registry, so I don't want to instance the class.
[quoted text clipped - 27 lines]
> }
> }
Nothing really wrong about your code (regMySoft needs to be static though), but you may want to check for the existance of the key, and if you need to create it, the registry key needs to have write permissions.
public static class Config
{
private static RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\MySoft", true);
private static RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
public static string MailServer
{
get
{
if (key == null)
{
softwareKey.CreateSubKey("MySoft");
key = softwareKey.OpenSubKey("MySoft", true);
key.SetValue("mailServer", "Default value");
}
return key.GetValue("mailServer").ToString();
}
set { key.SetValue("mailServer", value); }
}
}

Signature
Happy coding!
Morten Wennevik [C# MVP]
DArnold - 09 Jun 2007 13:24 GMT
> I'm trying to work with STATIC properties in C#. I have some properties
> I get from the registry, so I don't want to instance the class.
[quoted text clipped - 27 lines]
> }
> }
More something like this?
public class Config
{
private static RegistryKey regMySoft =
Registry.LocalMachine.OpenSubKey("SOFTWARE\\MySoft");
public static String MailServer
{
get
{
return regMySoft.GetValue("mailServer").ToString();
}
set
{
regMySoft.SetValue("mailServer", value);
}
}
}
}
x = Config.MailServer;
Config.MailServer = x;
Carlos Sosa Albert - 12 Jun 2007 19:09 GMT
Thanks a lot Darnold, it worked just fine!
=)
>> I'm trying to work with STATIC properties in C#. I have some properties I
>> get from the registry, so I don't want to instance the class.
[quoted text clipped - 51 lines]
> x = Config.MailServer;
> Config.MailServer = x;