none
C# Console Application- How can I validate data using .txt file? RRS feed

  • Question

  • I'm working on some sort of a login page and I want to validate a password only (no username cause I'm too lazy ;) ).

    I created a .txt file that is added by passwords that I think of (the password are added to the file from the same program). I am trying to write a code which will receive the password that the user writes ,as he tries to log in, and will try to find if this password exists in the list of passwords, which is in the txt file, to know if the user can get the access to his 'account' or not. Does that even a possible thing to do in C# Console Application? If it does, then what do I need to write?       (By the way, I didn't use the StreamWriter as many others write to create txt files, I used *this* code as I've seen recently in a YouTube video, if that helps you to answer my question...):

                    lines.Add(creationPassword);
                    File.WriteAllLines(filepath, lines);

    (creationPassword is the password that the user writes as he 'signs up' and that password is the password that is written in the txt file.)

    Apologize in advance for my bad Engilsh...

    Tuesday, April 3, 2018 7:08 PM

Answers

  • Hi yuvalmus,

    First of all if you want to validate passwords i wouldn't suggest you to save them in txt files since they are readable to anyone that way. But for example purposes i'll go on with that. Now the easiest way to achieve that is by using the StreamWriter to write to txt file and StreamReader to read a txt file. I would advice you to use these classes since that is why they are made for and thy are quite simple and understandable. In order to write on the text file you would create an instance of StreamWriter like so:

    StreamWriter sw = new StreamWriter(path);
    // where path is a string of your file location
    // or you could put in another attribute a bool that 
    // indicates if it should overwrite or not.
    StreamWriter sw = new StreamWriter(path, true);
    // true if you want to append, false if not

    Now in order to append text to the same line you would go ahead and use the .Write()method and you will pass it the string, bool, int or whatever value you want to write on the file. If you use the .Write method you will write on the same line each time.

    After that you can Flush(); the writer to clear the buffers of the instance.

    Always remember to Dispose the the StreamWriter object using the .Dispose method of the StreamWriter class to avoid any memory leaks or whatever.

    You can also use the .WriteLine() method to append a text value on a line and then automatically start writing to the next line if you want. Anyways everything you need to know about the StreamWriter you can view it on the class documentation by MSDN.

    Now about the StreamReader class. It's processing is just like the StreamWriter with the only difference that instead of writing the file you are reading the file. You create an instance of it like with the StreamWriter :

    StreamReader sr = new StreamReader(path);
    // where path is your file location

    You still Dispose it using the .Dispose() method just like with the StreamWriter to realise all it's resources.

    In order to Read the file- a ammount of characters- a block -or a line- or all the file do it by using some of it's methods described in the MSDN documentation of the class.

    .ReadLine() will read one line and then go to the next.

    .ReadToEnd() will read the whole file from the top to the bottom.

    In order to achieve what you want you could use the .ReadLine() method inside a while loop to read all the lines one by one and check if the correct password is found on the file and if so skip the rest of it by breaking the loop. Note that this will work only if each line has one and only one Password written on it. If you have multiple passwords on each line then i suggest you to think of a character that your passwords won't include, in order to split them accordingly.

    Hope this is helpfull.

    Best Regards,

    Konstantinos Pap

    • Edited by Konstantinos pap Wednesday, April 4, 2018 10:09 AM UPDATE
    • Marked as answer by yuvalmus Wednesday, April 4, 2018 1:59 PM
    Tuesday, April 3, 2018 7:46 PM

All replies

  • Hi yuvalmus,

    First of all if you want to validate passwords i wouldn't suggest you to save them in txt files since they are readable to anyone that way. But for example purposes i'll go on with that. Now the easiest way to achieve that is by using the StreamWriter to write to txt file and StreamReader to read a txt file. I would advice you to use these classes since that is why they are made for and thy are quite simple and understandable. In order to write on the text file you would create an instance of StreamWriter like so:

    StreamWriter sw = new StreamWriter(path);
    // where path is a string of your file location
    // or you could put in another attribute a bool that 
    // indicates if it should overwrite or not.
    StreamWriter sw = new StreamWriter(path, true);
    // true if you want to append, false if not

    Now in order to append text to the same line you would go ahead and use the .Write()method and you will pass it the string, bool, int or whatever value you want to write on the file. If you use the .Write method you will write on the same line each time.

    After that you can Flush(); the writer to clear the buffers of the instance.

    Always remember to Dispose the the StreamWriter object using the .Dispose method of the StreamWriter class to avoid any memory leaks or whatever.

    You can also use the .WriteLine() method to append a text value on a line and then automatically start writing to the next line if you want. Anyways everything you need to know about the StreamWriter you can view it on the class documentation by MSDN.

    Now about the StreamReader class. It's processing is just like the StreamWriter with the only difference that instead of writing the file you are reading the file. You create an instance of it like with the StreamWriter :

    StreamReader sr = new StreamReader(path);
    // where path is your file location

    You still Dispose it using the .Dispose() method just like with the StreamWriter to realise all it's resources.

    In order to Read the file- a ammount of characters- a block -or a line- or all the file do it by using some of it's methods described in the MSDN documentation of the class.

    .ReadLine() will read one line and then go to the next.

    .ReadToEnd() will read the whole file from the top to the bottom.

    In order to achieve what you want you could use the .ReadLine() method inside a while loop to read all the lines one by one and check if the correct password is found on the file and if so skip the rest of it by breaking the loop. Note that this will work only if each line has one and only one Password written on it. If you have multiple passwords on each line then i suggest you to think of a character that your passwords won't include, in order to split them accordingly.

    Hope this is helpfull.

    Best Regards,

    Konstantinos Pap

    • Edited by Konstantinos pap Wednesday, April 4, 2018 10:09 AM UPDATE
    • Marked as answer by yuvalmus Wednesday, April 4, 2018 1:59 PM
    Tuesday, April 3, 2018 7:46 PM
  • May This Help You

    Try the following code

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static List<string> lines;
            static string creationPassword="";
            static string filepath = "C:\\temp\\psw.txt";
            static void Main(string[] args)
            {
                if (!File.Exists(filepath))
                    File.Create(filepath);
                lines = new List<string>(File.ReadAllLines(filepath));
                Console.WriteLine("1.SignUP\n2.SignIn");
                if (Console.ReadKey().KeyChar=='1') signUp();
                else
                {
                    Console.WriteLine("\nEnter Your Password");
                    string password = Console.ReadLine();
                    if (signIn(password))
                        Console.WriteLine("You've successfully logged in.");
                    else
                        Console.WriteLine("Password not found");
                }
                Console.ReadKey();
            }
    
            static void signUp()
            {
                Console.WriteLine("Enter creation password");
                creationPassword = Console.ReadLine();
                lines.Add(creationPassword);
                File.WriteAllLines(filepath, lines);
                Console.WriteLine("You've successfully Signed Up.");
            }
    
            static Boolean signIn(string psw)
            {
                foreach (var item in lines)
                {
                    if (item == psw)
                        return true;
                }
                return false;
            }
        }
    }
    

    replace filepath with yours.

    Best Regards
    Vikram Manjare
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.

    Tuesday, April 3, 2018 7:51 PM
  • First of all, thank you for the long explanation. Second of all, I have three questions, if you'd like to answer:

    1)I tried to use the StreamWriter in a different code which I wrote two weeks ago and that method always deletes all the things I write in it and adds the new thing that I write. How can I use this method and keep adding stuff without deleting anything from the file? (maybe you answered it and I didn't pay attention...)

    2)Can you give me an example for a code that is using the .ReadLine() to read a txt file because I don't understand how will it read the file and how will it be used to check if the password is coorect?

    3) What other method do I have rather than txt file for what I want to do? (You wrote about it in the first sentence)

    I'm sorry if I ask to many questions... I just want to fully understand

    Wednesday, April 4, 2018 8:13 AM
  • Thank you for the code you sent! I prefer not to use it because I didn't actually understand all that writing to file and reading from file stuff and that's because I saw a YouTube video that just showed me the method without explaining too much... I tried to use some of the sentences but that caused me errors because I've already done the sign up page and there was a bit of a mess... Thank you very much! Hope you're not mad at me :)
    Wednesday, April 4, 2018 8:33 AM
  • Hey yuvalmus,

    1) First as i said in my reply, when configuring the StreamWriter you will pass through a second parameter called append and set it to true like so: ( in my above response i got it backwards i will edit that sorry for any inconvinience)

    StreamWriter sw = new StreamWriter(path, true);
    // true if you want to append, false if not

    If the file already exists it will append text on it instead of overwrite it.

    2) You should read in a while loop one line at a time and compare it to your password like so:

    string line = string.Empty; while((line = file.ReadLine()) != null) { if(line == mypassword) { MessageBox.Show("Password Correct, you are logged in", "Success!"); break; } }

    Also note that this will require you to have ONE and only one password on each line.

    If you have multiple passwords on each line you would think of a character that your passwords won't include in order to split the line in a string array and compare the array with your password.

    3) You could make a database and store all the passwords you want in it, you could do it on a config file using the application settings at visual studio. you could make a .xml file and store all the values in it (for security reasons you could encrypt these values as well) and more generally anything that is more secure and won't cause your application to crash during runtime. Because think the possibility of a user going into your application stuff and changing the values. Then he could log in with whatever password he wants or maybe cause the application to crash.

    If you have any more questions please let me know.

    Best Regards,

    Konstantinos Pap


    Wednesday, April 4, 2018 10:07 AM
  • One more question- in the code you wrote, it caused me an error in  the file.ReadLine() sentence. What is that 'file' that you wrote there and why c# doesn't let me write the ReadLine?

    I tried to switch the 'file' word with filepath (which is assigned to the txt file) but it just doesn't work...

    • Edited by yuvalmus Wednesday, April 4, 2018 12:48 PM
    Wednesday, April 4, 2018 12:47 PM
  • That file is not the file location but the StreamReader instance. Here is the site i got it from.Sorry for not being more specific on that.

    Best Regards,

    Konstantinos Pap

    Wednesday, April 4, 2018 1:00 PM