locked
Validate if string exist in txt file and update previously used txt file RRS feed

  • Question

  • I am using jquery ajax to insert data into txt file. Txt file contains three items UserName, Password and IsUsed. I am trying to return message if password exist for a specific username return message password already exist. If not Insert data into txt file. There are few scenario which I am trying to add

    1. When user enter username and Password. Check if the password is already used. In below sample table if user enters UserName: Sam and Password: Sam789. Program should insert new password. While inserting password mark previous password IsUsed as 1 and insert new row Sam,Sam789,0
    2. If same password entered again. Return message - "Password already used."

    Sample Text File

    UserName,Password,IsUsed
    Sam,Sam123,1
    Sam,Sam456,1
    Sam,Sam879,0
    Tom,Abc147,0

    I am not how I can achieve this. Below is somewhat I think need to be used but not sure how to implement. Can anyone can help please?

    string[] lines = File.ReadAllLines(path);
    lines = lines.GroupBy(x => [username]).Where(g => g.Count() > 1).Select(g => g.Key).ToArray();
    File.WriteAllLines(newPath, lines):




    Jay P


    • Edited by jazz1010 Sunday, June 14, 2020 7:04 PM
    Sunday, June 14, 2020 7:04 PM

All replies

  • The code you have is reading the file as a set of strings, with no structure.  There is no "username" field.

    If you want to continue with this design, then I think you want to create a class called "Identity" that has three fields, username, password, used.  Then you could create an "IdentityList" class that contains an array or a list of Identity objects.  Now you can write IdentityList.Serialize and IdentityList.Unserialize to write the list out to disk (including the header) and read the list from disk.  Once you've done that, you can write code to query the list for existing values and add a new value.  I'm not sure LINQ is really right for that, because you need to take several different actions.  You might add IdentityList.IsPasswordUsed that searches for a match on username and password.  You might add IdentityList.AddNew that adds a new password line, and checks to see if there is a record for the same username with "used" set to 0.

    So, your code could become
        IdentityList users = new IdentityList();
        users.ReadFrom( path );
        if( users.IsPasswordUsed( username, password ) {
            // Complain that password has already been used
        } else {
            users.AddNew( username, password );
            users.WriteTo( path );
        }

    The nice thing about that is that it hides the implementation of IdentityList from the outer code.  We don't care what the internal field names or I/O methods are.

    I do feel the need to point out that it would be ethically irresponsible of you to store passwords in plain text like that.  By stealing one file, your entire user base is compromised.  If the information you're protecting is of minimal importance, that might be OK, but in virtually every circumstance you should be using one-way encryption to store your passwords.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Monday, June 15, 2020 1:07 AM
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace StringsTest1
    {
    
        public class User
        {
    
            public string Username;
            public string Password;
            public bool IsUsed;
    
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    
                string filename = @"D:\tmp\1.txt";
    
                string[] lines = File.ReadAllLines(filename);
                List<User> lsUsers = new List<User>();
                foreach (string line in lines.Skip(1))
                {
                    string[] c = line.Split(',');
                    if (c.Length >= 3)
                        lsUsers.Add(new User { Username = c[0], Password = c[1], IsUsed = c[2] != "0" });
                }
    
                Console.WriteLine("Enter username:");
                string strUser = Console.ReadLine();
                User user = lsUsers.FirstOrDefault(x => x.Username == strUser);
                if (user != null)
                {
                    Console.WriteLine("Enter new password:");
                    string strPassword = Console.ReadLine();
                    if (!lsUsers.Any(x => x.Username == strUser && x.Password == strPassword))
                    {
                        foreach(User user2 in lsUsers)
                        {
                            if (user2.Username == strUser)
                                user2.IsUsed = true;
                        }
                        lsUsers.Add(new User { Username = strUser, Password = strPassword, IsUsed = false });
    
                        Console.WriteLine("User added successfully!");
    
                    }
                    else
                    {
                        Console.WriteLine("Password already used!");
                    }
    
                }
                else
                {
                    Console.WriteLine("User not found!");
                }
                    
    
                List<string> lsLinesOut = new List<string> { "UserName,Password,IsUsed" };
                foreach (User user3 in lsUsers)
                {
                    lsLinesOut.Add(string.Format("{0},{1},{2}", user3.Username, user3.Password, user3.IsUsed ? "1":"0"));
                }
    
                File.WriteAllLines(filename, lsLinesOut);
    
            }
        }
    }
    
    

    Software development blog
    • Proposed as answer by Artem Moroz Monday, June 15, 2020 12:15 PM
    Monday, June 15, 2020 11:57 AM