0

I apologize if the question is very noobish, I have been only learning for 3 weeks. It's kind of overwhelming, even if you do simple things like I do.

So I'm trying to create a program that manages "accounts" as practice and puts the users and the corresponding passwords in two separate .txt files. Each line translates into a user or password accordingly. I use both lists and arrays, because arrays are easier to use in certain situations, but lists can have varying length.

I ran into a problem when I was creating a function for the program that changes the "administrator", the first user in the list, to a user, whose ID is given in form of user input. I read about how to do this, but I seem to have failed, as the intended swap does absolutely nothing. Users are returned to the list in the original order. Any further observation of why my code is messed up is also welcome.

Here's the actual code to this function of the program:

else if (input.Contains("changeadmin"))
{
    foreach (string y in idKeysLocArray) //checks every line for username
    {
        if (input.Contains(y))
        {
            string[] idKeysLocArray2 = File.ReadAllLines(idKeysLoc); // creates new arrays in case .txt was updated by different function before
            string[] passKeysLocArray2 = File.ReadAllLines(passKeysLoc);

            static void Swap(ref string a, ref string b)  // create function to swap two members of an array
            {
                string temp = a;
                a = b;
                b = temp;
            }

            Swap(ref idKeysLocArray2[0], ref idKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]); //using function to swap array members
            Swap(ref passKeysLocArray2[0], ref passKeysLocArray2[Array.IndexOf(idKeysLocArray2, y)]);

            var idKeysLocArray2List = idKeysLocArray2.ToList();
            var passKeysLocArray2List = passKeysLocArray2.ToList();

            foreach (string h in idKeysLocArray2List) // to check success
            { 
                Console.WriteLine(h);
            }
            TextWriter w7 = new StreamWriter(idKeysLoc); // write swapped values to .txt file
            foreach (string s in idKeysLocArray2List)
                w7.WriteLine(s);

            w7.Close();

            TextWriter w8 = new StreamWriter(passKeysLoc);
            foreach (string s in passKeysLocArray2List)
                w8.WriteLine(s);

            w8.Close();
        }
    }
}
antl bvc
  • 1
  • 1
  • The `Swap` itself is fine. Double check that it is being called, and that correct parameters are being passed to it. – GSerg May 24 '20 at 15:48
  • thanks. i figured it out. the ids location in the array was used to determine which password to swap for which, and since the id was changed before the password, the password swap failed to happen, since the value that the index of provided for the password swap was always 0. – antl bvc May 24 '20 at 16:21

0 Answers0