简体   繁体   English

如何更改仅适用于正确用户的存储在文本文件中的用户名和密码

[英]how to change a username and password stored in a text file only for the correct user

i am currently making a application for my a level computing coursework. 我目前正在为我的水平计算课程申请。 for my coursework i am required to make a login and registration system which requires me to store the user details in a text file this is only for my coursework so security isent important. 对于我的课程,我需要制作一个登录和注册系统,该系统要求我将用户详细信息存储在文本文件中,这仅用于我的课程,因此安全性至关重要。 my registration and login system works fine but i am also required to have a change account details screen in which the user can change their username and password. 我的注册和登录系统工作正常,但我还必须具有一个“更改帐户详细信息”屏幕,用户可以在其中更改其用户名和密码。

my problem is that my code that i have currently changes the password for every user with the same password ie if 2 users have password123 as a password both their passwordds gets changed to the new password 我的问题是我当前已为具有相同密码的每个用户更改密码的代码,即如果2个用户将password123作为密码,则他们的两个密码都更改为新密码

 private void btnUpdatePassword_Click(object sender, EventArgs e)
    {
        string oldusername = txtBoxOldUsername.Text;
        string newusername = txtBoxNewUsername.Text;
        string oldpassword = txtBoxOldPassword.Text;
        string newpassword = txtBoxNewPassword.Text;

        string text = File.ReadAllText("users.txt");
        text = text.Replace(oldpassword, newpassword).Replace(oldusername, newusername);
        File.WriteAllText("users.txt", text);
    }

my problem is that i dont know how to change the password for only the correct user. 我的问题是我不知道如何仅更改正确用户的密码。 it would be great if anyone could help thanks. 如果有人可以帮助,那就太好了。 also i HAVE to use a text file to do this meaning i cant use jason on xml etc 我也不得不使用文本文件来做到这一点,我不能在xml等上使用杰森

this is what my text file looks like 这是我的文本文件的样子

first user ~username~password 第一个用户〜用户名〜密码

second user ~username123~password 第二个用户〜username123〜password

third user ~username1234~password 第三个用户〜username1234〜password

and this is the code i use to write to the text file 这是我用来写入文本文件的代码

FileStream fileStream = new FileStream("users.txt", FileMode.Append, FileAccess.Write);
                        StreamWriter streamWriter = new StreamWriter(fileStream);

                        try
                        {
                            streamWriter.WriteLine(fullname + "~" + username + "~" + password + "~" + lastlogin);

                            MessageBox.Show("User registered successfully", "Registration Successful");

                            this.Hide();
                            var homeForm = new HomeForm();
                            homeForm.Closed += (s, args) => this.Close();
                            homeForm.Show();

                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Error registering the user", "Please try again");
                        }
                        finally
                        {
                            streamWriter.Close();
                            fileStream.Close();
                        }

Here is an idea on how to implement it. 这是有关如何实现它的想法。 My first suggestion is to add a comma deliminator to your text file so your values in users.txt will be in the following form 我的第一个建议是在文本文件中添加逗号分隔符,以便在users.txt中的值将采用以下格式

second user~username123~password,
third user~username1234~password,
first user~username~smelly,

Import all the users from users.txt at once and split them by our deliminator ',' 一次从users.txt导入所有用户,然后由我们的分隔符','进行划分

 var users = File.ReadAllText(@"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));

Note this clause .Where(x=> !String.IsNullOrWhiteSpace(x ) will be needed because when I rewrite the file , for simplicity sake I add a comma to each entry. As last entry will have a comma we end up with an extra empty object. This clause will rectify it. 请注意此子句.Where(x=> !String.IsNullOrWhiteSpace(x )是必需的,因为当我重写文件时,为简单起见,我在每个条目中添加了一个逗号。空对象,此子句将对其进行纠正。

Create a class which will contains all the user properties: 创建一个包含所有用户属性的类:

    private class User
    {
        public string Name { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        public string PrepareForFile()
        {
            return Name + "~" + UserName + "~" + Password + ",";
        }
    }

Loop through all the retrieved users information from file and build a list of user: 循环浏览文件中所有检索到的用户信息,并建立用户列表:

        List<User> myUsers = new List<User>();
        foreach (var user in users)
        {
            var information = user.Split('~');
            User temp = new User();
            temp.Name = information[0].Trim();
            temp.UserName = information[1].Trim();
            temp.Password = information[2].Trim();
            myUsers.Add(temp);
        }

Now you have a manageable structure and you can perform all the desired operations. 现在您有了一个易于管理的结构,可以执行所有所需的操作。 Once finished use the method PrepareForFile() to create a string like second user~username123~password to be written into file. 完成后,使用方法PrepareForFile()创建要写入文件的字符串,例如second user~username123~password

Putting it all together(this is a console app): 放在一起(这是一个控制台应用程序):

  static class Program
    {
        private class User
        {
            public string Name { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }

            public string PrepareForFile()
            {
                return Name + "~" + UserName + "~" + Password + ",";
            }
        }

        static void Main(string[] args)
        {
            var users = File.ReadAllText(@"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));

            List<User> myUsers = new List<User>();
            foreach (var user in users)
            {
                var information = user.Split('~');
                User temp = new User();
                temp.Name = information[0].Trim();
                temp.UserName = information[1].Trim();
                temp.Password = information[2].Trim();
                myUsers.Add(temp);
            }

            var selectedUser = myUsers.Where(x => x.UserName == "username").SingleOrDefault();
            myUsers.Remove(selectedUser);
            selectedUser.Password = "Leo";
            myUsers.Add(selectedUser);

            List<string> formatForFile = new List<string>();
            foreach(var item in myUsers)
            {
                formatForFile.Add(item.PrepareForFile());
            }
            File.WriteAllLines(@"C:\users.txt", formatForFile.ToArray());
        }
    }

Changing username1234 password from "password" to "AlexLeo": 将用户名1234密码从“密码”更改为“ AlexLeo”:

Before 之前

在此处输入图片说明

After

在此处输入图片说明

You can store the username with the password when saving the password and delete the username when it is extracted from the password and add the username when adding the password. 您可以在保存密码时将用户名和密码一起存储,并在从密码中提取用户名时将其删除,并在添加密码时添加用户名。 for example: 例如:

private void btnUpdatePassword_Click(object sender, EventArgs e)
{
    string oldusername = txtBoxOldUsername.Text;
    string newusername = txtBoxNewUsername.Text;
    string oldpassword = txtBoxOldPassword.Text;
    string newpassword = txtBoxNewPassword.Text;

    string text = File.ReadAllText("users.txt");
    text = text.Replace(oldpassword + oldusername, newpassword + newusername).Replace(oldusername, newusername);
    File.WriteAllText("users.txt", text);
}

Based on your updated OP 根据您更新的OP

string str = System.IO.File.ReadAllText(fileName);
var users = str.Split(new []{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries)
            .Select(x=>
            {
              var strArray = x.Split(new []{"~"},StringSplitOptions.RemoveEmptyEntries);
              return new 
               { 
                 FirstName = strArray[0],
                 User = strArray[1],
                 Password = strArray[2]
               };
            }
            );

var usernameToUpdate = "username123";
var newPassword = "Thisisnewpassword";

var updatedList = users.Select(x => x.User.Equals(usernameToUpdate) ? 
                        $"{x.FirstName} ~{x.User}~{newPassword}"
                        : $"{x.FirstName} ~{x.User}~{x.Password}").ToList();

var newFileData = String.Join(Environment.NewLine, 
                   updatedList);
File.WriteAllText(fileName, newFileData);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从文本文件中验证用户名和密码? | Winforms C# - How to validate username and password from text file? | Winforms C# 如何设置正确的用户名和密码文本框? - How to set the correct username and password textboxes? 由于用户不存在/密码/用户名正确而导致尝试登录网站失败时如何返回消息? - How to return a message when a try to login to the website failed, because the user does not exist/password/username arent correct? 如何检查用户输入的用户名密码和数据库名称是否正确? - How can I check if user enter correct username password and database name? 如何在控制台中创建登录名,在控制台中我使用存储在文件C#中的用户名和密码进行身份验证 - How to create a login in console where I authenticate using an username and password stored in a file c# 使用Entity Framework时,如何将数据库用户名和密码安全地存储在web.config文件中 - How can a database username and password be stored securely in a web.config file when using Entity Framework 如何获取当前用户的用户名,密码和域 - How to get username, password and domain of current user 从正确的用户名行中获取密码表单文件 - Take password form file from the correct username line 如何获取和更改Windows凭据用户名和密码 - How to Get and Change Windows Credential Username and Password 如何通过用户名和密码注册用户并通过会员身份确认密码和电子邮件? - How to register user by username and password and confirm password and email by membership?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM