C# 错误发生在特定代码行之后

C# 错误发生在特定代码行之后,c#,winforms,C#,Winforms,我的错误是:对象引用未设置为对象的实例。我不认为这是导致问题的实际行,但它出现了: mainWindow.ChangeTextBox = stringBuilder.ToString(); 似乎它会在代码的第一行上紧接着出现错误: string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass); string decrypted = en.Decrypt(encrypted, user, p

我的错误是:
对象引用未设置为对象的实例。
我不认为这是导致问题的实际行,但它出现了:

mainWindow.ChangeTextBox = stringBuilder.ToString();
似乎它会在代码的第一行上紧接着出现错误:

        string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
        string decrypted = en.Decrypt(encrypted, user, pass);
原因可能是什么

AddEntryWindow.cs

using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;

namespace Store_Passwords_and_Serial_Codes
{
    public partial class AddEntryWindow : Form
    {
        string user, pass;
        // Initializind ArrayList to store all data needed to be added or retrived.
        private ArrayList addedEntry = new ArrayList();

        // Initializing MainWindow form.
        MainWindow mainWindow;

        // Making authentication possible.
        // AuthenticateUser authenticateUser = new AuthenticateUser();

        EncryptDecrypt en = new EncryptDecrypt();

        // Default constructor to initialize the form.
        public AddEntryWindow()
        {
            InitializeComponent();
        }

        public AddEntryWindow(string user, string pass)
            : this() // important!
        {
            this.user = user;
            this.pass = pass;
        }


        public AddEntryWindow(MainWindow viaParameter) : this()
        {
            mainWindow = viaParameter;
        }

        private void AddEntryWindow_Load(object sender, EventArgs e)
        { }

        private void btnAddEntry_Click(object sender, EventArgs e)
        {
            // Making sure that type is selected.
            if (cmbType.SelectedIndex == -1)
            {
                MessageBox.Show("Please select entry type!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // Each field must be filled for specified type.
            // Here we are checking if all fields were filled.
            else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
            {
                MessageBox.Show("Please fill all the fields!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                int totalEntries = 0;

                if(cmbType.SelectedIndex == 0)
                    addedEntry.Add(new AddPC(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text));

                else if(cmbType.SelectedIndex == 1)
                    addedEntry.Add(new AddWebSite(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text, txtURL.Text));

                else if(cmbType.SelectedIndex == 2)
                    addedEntry.Add(new AddSerialCode(cmbType.Text, 
                        txtSoftwareName.Text, txtSerialCode.Text));

                StringBuilder stringBuilder = new StringBuilder();

                foreach (var list in addedEntry)
                {
                    if (list is AddPC)
                    {
                        totalEntries++;
                        AddPC tmp = (AddPC)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddWebSite)
                    {
                        totalEntries++;
                        AddWebSite tmp = (AddWebSite)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddSerialCode)
                    {
                        totalEntries++;
                        AddSerialCode tmp = (AddSerialCode)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                }

                MessageBox.Show(user + pass);

                string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
                string decrypted = en.Decrypt(encrypted, user, pass);


                    //+ Environment.NewLine +
                    //encrypted + Environment.NewLine + decrypted);

                mainWindow.ChangeTextBox = stringBuilder.ToString();

                //mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";

                // Clearing all fields.
                //ClearFields();
            }
        }

        private void btnClear_Click(object sender, EventArgs e){}
        private void btnClose_Click(object sender, EventArgs e){}
        private void cmbType_SelectedIndexChanged(object sender, EventArgs e){}
    }
}
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Store_Passwords_and_Serial_Codes
{
    class EncryptDecrypt
    {
        string input, userName, password;

        RijndaelManaged Crypto = new RijndaelManaged();

        public EncryptDecrypt()
        {
        }

        public EncryptDecrypt(string input, string userName, string password)
        {
            this.input = input;
            this.userName = userName;
            this.password = password;
        }

        public string Encrypt(string PlainText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

            this.input = PlainText;

            if (string.IsNullOrEmpty(PlainText))
                return "";

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
            byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);

            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

            RijndaelManaged SymmetricKey = new RijndaelManaged();

            SymmetricKey.Mode = CipherMode.CBC;

            byte[] CipherTextBytes = null;

            using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream())
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }

            SymmetricKey.Clear();
            return Convert.ToBase64String(CipherTextBytes);
        }

        public string Decrypt(string CipherText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

             if (string.IsNullOrEmpty(CipherText))
                 return "";

             byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);

             byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
             byte[] CipherTextBytes = Convert.FromBase64String(CipherText);

             PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

             byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

             RijndaelManaged SymmetricKey = new RijndaelManaged();

             SymmetricKey.Mode = CipherMode.CBC;

             byte[] PlainTextBytes = new byte[CipherTextBytes.Length];

             int ByteCount = 0;

             using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
             {
                 using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                 {

                     using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                     {
                         ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                         MemStream.Close();
                         CryptoStream.Close();
                     }
                 }
             }

             SymmetricKey.Clear();
             return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
         }
    }
}
Encrypt Decrypt.cs

using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;

namespace Store_Passwords_and_Serial_Codes
{
    public partial class AddEntryWindow : Form
    {
        string user, pass;
        // Initializind ArrayList to store all data needed to be added or retrived.
        private ArrayList addedEntry = new ArrayList();

        // Initializing MainWindow form.
        MainWindow mainWindow;

        // Making authentication possible.
        // AuthenticateUser authenticateUser = new AuthenticateUser();

        EncryptDecrypt en = new EncryptDecrypt();

        // Default constructor to initialize the form.
        public AddEntryWindow()
        {
            InitializeComponent();
        }

        public AddEntryWindow(string user, string pass)
            : this() // important!
        {
            this.user = user;
            this.pass = pass;
        }


        public AddEntryWindow(MainWindow viaParameter) : this()
        {
            mainWindow = viaParameter;
        }

        private void AddEntryWindow_Load(object sender, EventArgs e)
        { }

        private void btnAddEntry_Click(object sender, EventArgs e)
        {
            // Making sure that type is selected.
            if (cmbType.SelectedIndex == -1)
            {
                MessageBox.Show("Please select entry type!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // Each field must be filled for specified type.
            // Here we are checking if all fields were filled.
            else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
                (cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
            {
                MessageBox.Show("Please fill all the fields!", "Error!", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                int totalEntries = 0;

                if(cmbType.SelectedIndex == 0)
                    addedEntry.Add(new AddPC(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text));

                else if(cmbType.SelectedIndex == 1)
                    addedEntry.Add(new AddWebSite(cmbType.Text, 
                        txtUserName.Text, txtPassword.Text, txtURL.Text));

                else if(cmbType.SelectedIndex == 2)
                    addedEntry.Add(new AddSerialCode(cmbType.Text, 
                        txtSoftwareName.Text, txtSerialCode.Text));

                StringBuilder stringBuilder = new StringBuilder();

                foreach (var list in addedEntry)
                {
                    if (list is AddPC)
                    {
                        totalEntries++;
                        AddPC tmp = (AddPC)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddWebSite)
                    {
                        totalEntries++;
                        AddWebSite tmp = (AddWebSite)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                    else if (list is AddSerialCode)
                    {
                        totalEntries++;
                        AddSerialCode tmp = (AddSerialCode)list;
                        stringBuilder.Append(tmp.ToString());
                    }
                }

                MessageBox.Show(user + pass);

                string encrypted = en.Encrypt(stringBuilder.ToString(), user, pass);
                string decrypted = en.Decrypt(encrypted, user, pass);


                    //+ Environment.NewLine +
                    //encrypted + Environment.NewLine + decrypted);

                mainWindow.ChangeTextBox = stringBuilder.ToString();

                //mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";

                // Clearing all fields.
                //ClearFields();
            }
        }

        private void btnClear_Click(object sender, EventArgs e){}
        private void btnClose_Click(object sender, EventArgs e){}
        private void cmbType_SelectedIndexChanged(object sender, EventArgs e){}
    }
}
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Store_Passwords_and_Serial_Codes
{
    class EncryptDecrypt
    {
        string input, userName, password;

        RijndaelManaged Crypto = new RijndaelManaged();

        public EncryptDecrypt()
        {
        }

        public EncryptDecrypt(string input, string userName, string password)
        {
            this.input = input;
            this.userName = userName;
            this.password = password;
        }

        public string Encrypt(string PlainText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

            this.input = PlainText;

            if (string.IsNullOrEmpty(PlainText))
                return "";

            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
            byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);

            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

            RijndaelManaged SymmetricKey = new RijndaelManaged();

            SymmetricKey.Mode = CipherMode.CBC;

            byte[] CipherTextBytes = null;

            using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream())
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                    {
                        CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                        CryptoStream.FlushFinalBlock();
                        CipherTextBytes = MemStream.ToArray();
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }

            SymmetricKey.Clear();
            return Convert.ToBase64String(CipherTextBytes);
        }

        public string Decrypt(string CipherText, string pass, string usrName)
        {
            string HashAlgorithm = "SHA1"; 
            int PasswordIterations = 2;
            string InitialVector = "OFRna73m*aze01xY";
            int KeySize = 256;

             if (string.IsNullOrEmpty(CipherText))
                 return "";

             byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);

             byte[] SaltValueBytes = Encoding.ASCII.GetBytes(usrName);
             byte[] CipherTextBytes = Convert.FromBase64String(CipherText);

             PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(pass, SaltValueBytes, HashAlgorithm, PasswordIterations);

             byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);

             RijndaelManaged SymmetricKey = new RijndaelManaged();

             SymmetricKey.Mode = CipherMode.CBC;

             byte[] PlainTextBytes = new byte[CipherTextBytes.Length];

             int ByteCount = 0;

             using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
             {
                 using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                 {

                     using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                     {
                         ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                         MemStream.Close();
                         CryptoStream.Close();
                     }
                 }
             }

             SymmetricKey.Clear();
             return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
         }
    }
}

关于。

mainWindow
仅在此构造函数中设置:
公共AddEntryWindow(mainWindow viaParameter)
,如果使用此构造函数,则不设置:
公共AddEntryWindow(字符串用户,字符串传递)
或默认构造函数


您可以始终在引发异常的行上放置断点,并检查每个变量。

您应该将mainWindow设置为mainWindow的实例

在下面的构造函数中,您没有这样做

    public AddEntryWindow(string user, string pass)
        : this() 
    {
        this.user = user;
        this.pass = pass;
    }


    public AddEntryWindow(MainWindow viaParameter, string user, string pass)
        : this() 
    {

        mainWindow = viaParameter;
        this.user = user;
        this.pass = pass;
    }

我想你是对的。我可能忘记了MainWindow.cs文件中的一些代码。需要再检查一下吗