如何打破do while循环?

时间:2015-01-09 20:14:14

标签: c# login text-files

我是编码的新手,并且一直在尝试使用文本文件进行登录(我知道我知道它对文本文件的练习不安全)

namespace text_file_login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btn_register_Click(object sender, EventArgs e)
        {
            StreamWriter user_reg =
                new StreamWriter(@"E:\SSD\Controled Assesment\text file login\text file login\username.txt");
            StreamWriter pass_reg =
                new StreamWriter(@"E:\SSD\Controled Assesment\text file login\text file login\password.txt");

            user_reg.WriteLine(txt_user.Text);
            user_reg.Close();
            pass_reg.WriteLine(txt_pass.Text);
            pass_reg.Close();

            MessageBox.Show("Register was sucessful");
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            string user = "";
            string pass = "";
            int user_line_number = 0;
            int pass_line_number = 0;
            StreamReader user_login =
                new StreamReader(@"E:\SSD\Controled Assesment\text file login\text file login\username.txt");
            StreamReader pass_login =
                new StreamReader(@"E:\SSD\Controled Assesment\text file login\text file login\password.txt");
            do
            {
                user = user_login.ReadLine();
                user_line_number++;
                if (user == txt_user.Text)
                {
                    do
                    {
                        pass = pass_login.ReadLine();
                        pass_line_number++;
                        if ((pass == txt_pass.Text) && (user_line_number == pass_line_number))
                        {
                            MessageBox.Show("Login was succesful");
                            //this.Close();
                        }
                        else
                        {
                            if ((user_line_number > pass_line_number) || (user_line_number < pass_line_number))
                            {
                                MessageBox.Show("Wrong Password");
                            }
                        }
                    } while (pass_login.Peek() != -1);
                }
            } while (user_login.Peek() != -1);
        }
    }
}

登录正常,寄存器有效。但是,如果用户名或密码错误,我很确定这将永远循环。如何结束循环,以便如果用户名或密码错误,我可以显示一个消息框? 我不是太多融合了多个用户名,但是如果你能解决这个问题呢?

如果写得不好,请抱歉。我是初学者

1 个答案:

答案 0 :(得分:5)

如果你想从一个循环中“破解”,那么你就是这样做的:

do {
    if (something)
        break;
}
while (condition)