在尝试修复 Null 值时,我遇到了 C# 问题(我是新手)。因此,我有一个变量“verif”(String verif = String.Empty;),我用它从 Windows 注册表中读取一些键。如果密钥存在,我的代码可以工作,但是当它不存在时,我收到错误“NullReferanceException 未处理”。我尝试了几种方法来捕获异常,放置一个“If”语句,但我失败了。我的代码是这样的:
RegistryKey key_user;
RegistryKey key_pwd;
String code = String.Empty;
String tara = String.Empty;
String tot = String.Empty;
String pwd_mdw = String.Empty;
String user_mdw = String.Empty;
String user_uca = String.Empty;
String pwd_uca = String.Empty;
String verif = String.Empty;
private void button1_Click(object sender, EventArgs e)
{tot = listBox1.SelectedValue.ToString();
//MessageBox.Show(tot);
tara = tot.Substring(tot.Length - 2, 2);
//MessageBox.Show(tara);
code = listBox1.SelectedValue.ToString().Substring(0, 2);
user_mdw = textBox1.Text;
//MessageBox.Show(user_mdw);
pwd_mdw = textBox2.Text;
//MessageBox.Show(pwd_mdw);
if (code == "CC")
{
verif = Registry.CurrentUser.OpenSubKey(@"Software\TDCredentials").GetValue("user_mdw_" + tara + "_CC").ToString();
MessageBox.Show("Verif",verif);
MessageBox.Show(user_mdw, "user_mdw");
if (verif==null)
{
key_user = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_user.SetValue("user_mdw_" + tara + "_CC", user_mdw);
key_user.Close();
key_pwd = Registry.CurrentUser.CreateSubKey("Software\\TDCredentials");
key_pwd.SetValue("pass_mdw_" + tara + "_CC", pwd_mdw);
key_pwd.Close();
MessageBox.Show("User and Password inserted successfully!");
textBox1.Clear();
textBox2.Clear();
}
else
{...
有什么提示吗?非常感谢,博格丹。