0

lets say i have 5 lines within a txt file called users.txt each line has the following information

username:password

how would i go about spliting each line within a txt file and store the username as one string and password as the other.

I have the code to grab a random line using this code. This code is used for another part of my project aswell so I dont want the code to be altered. I was thinking after the line has been grabbed call another function but I have no idea on how to split it with the :

private static string GetRandomLine(string file)
    {
        List<string> lines = new List<string>();

        Random rnd = new Random();

        int i = 0;


        try
        {
            if (File.Exists(file))
            {
                //StreamReader to read our file
                StreamReader reader = new StreamReader(file);

                //Now we loop through each line of our text file
                //adding each line to our list
                while (!(reader.Peek() == -1))
                    lines.Add(reader.ReadLine());

                //Now we need a random number
                i = rnd.Next(lines.Count);

                //Close our StreamReader
                reader.Close();

                //Dispose of the instance
                reader.Dispose();

                //Now write out the random line to the TextBox
                return lines[i].Trim();

            }
            else
            {
                //file doesn't exist so return nothing
                return string.Empty;
            }
        }
        catch (IOException ex)
        {
            MessageBox.Show("Error: " + ex.Message);
            return string.Empty;
        }
    }
mintuz
  • 735
  • 1
  • 18
  • 40

7 Answers7

4

You should be able to use string.Split:

 string line = GetRandomLine(file);
 string[] parts = line.Split(':');

 string user = parts[0];
 string pass = parts[1];

That being said, you may also want to add error checking (ie: make sure parts has 2 elements, etc).

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

To split the string is simple:

string[] components = myUserAndPass.Split(':'); 
string userName = components[0];
string passWord = components[1];
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
  • No need to create the `new char[] {`, since String.Split is defined as `(params char[] separator)` - See: http://msdn.microsoft.com/en-us/library/b873y76a.aspx – Reed Copsey Mar 11 '11 at 20:39
  • @Reed You are correct, I was thinking about the `String.Join()` syntax; I actually started typing String.Split, and then went back and fixed that part. =) – CodingGorilla Mar 11 '11 at 20:40
0

Try to read the following stackoverflow pages:

C# Tokenizer - keeping the separators

Does C# have a String Tokenizer like Java's?

Community
  • 1
  • 1
SOUser
  • 3,802
  • 5
  • 33
  • 63
0

Use the Split() method. For example, in this case

string[] info = lines[i].Split(':');

info[0] will have the username and info[1] will have the password.

rohit89
  • 5,745
  • 2
  • 25
  • 42
0

Try something like this...

string []split = line.Split(':');

string username = split[0];

string pwd = split[1];

Rockie
  • 58
  • 7
0

Reed Corpsey gave a nice answer already, so instead of giving another solution, I'd just like to make one comment about your code. You can use the Using statement to handle the StreamReader Close and Dispose method calling for you. This way if an error happens, you don't have to worry that the Stream is left open.

Changing your code slightly would make it look like:

//StreamReader to read our file
using(StreamReader reader = new StreamReader(file))
{
    //Now we loop through each line of our text file
    //adding each line to our list
    while (!(reader.Peek() == -1))
        lines.Add(reader.ReadLine());

    //Now we need a random number
    i = rnd.Next(lines.Count);
}
//Now write out the random line to the TextBox
return lines[i].Trim();
jb.
  • 9,921
  • 12
  • 54
  • 90
0

This is much cleaner, and handles cases where the password might contain ':'s

Of course I would expect you to ensure that passwords are not plain text and hashed password's don't contain any ':'s; But just in case they do, this is what would work:

Split() will cause other problems.

        bool GetUsernamePassword(string line, ref string uname, ref string pwd)
        {
            int idx = line.IndexOf(':') ;
            if (idx == -1)
                return false;
            uname = line.Substring(0, idx);
            pwd = line.Substring(idx + 1);
            return true;
        }

.

            string username_password = "username:password";
            string uname = String.Empty;
            string pwd = String.Empty;
            if (!GetUsernamePassword(username_password, ref uname, ref pwd))
            {
                // Handle error: incorrect format
            }
            Console.WriteLine("{0} {1} {2}", username_password, uname, pwd);

btw. having said the above this won't work (like all other solutions before this one) if the username has ':' :P But this will handle the case where password has ':'.

chkdsk
  • 1,187
  • 6
  • 20