1

I'm trying to make a basic login for my console app. I store the user data in a .txt file like this: ID;Name;IsAdmin. The txt has several lines.

In the app I want to store user data in a struct User array. I can't seem to find the method to read the file, split and put the different data to the right place. This is what I have so far:

Loading user data to struct array

public static void LoadIDs()
        {
            int entries = FileHandling.CountRows(usersPath);
            User[] users = new User[entries]; //Length depends on how many lines are in the .txt

            for (int i = 0; i < users.Length; i++)
            {
                users[i] = new User(1,"a",false); //ID(int), name, isAdmin [This is where I want to put the data from the .txt]
            }
        }

Reading and spliting the text

public static string ReadFileToArray(string path)
        {
            String input = File.ReadAllText(path);

            foreach (var record in input.Split('\n'))
            {
                foreach (var data in record.Split(';'))
                {
                    return data;
                }
            }

            return null;
        }

I know that this doesn't work at all this way but my knowledge is limited yet and I cannot think of other solutions.

5
  • 2
    You'll have to read the file line by line and create a User instance for every line Commented Dec 13, 2019 at 21:37
  • 4
    Use File.ReadAllLines instead of ReadAllText Commented Dec 13, 2019 at 21:39
  • 1
    Think about what your ReadFileToArray is even doing.. You're splitting by line, then splitting each line by ;, and then you just return the first thing... why would you want to do that? Commented Dec 13, 2019 at 21:39
  • You're over complicating this if you want to keep it basic. Skip the file reading all together and just store the data in memory. Commented Dec 13, 2019 at 21:51
  • 1
    use File.ReadLines instead of File.ReadAllLines Commented Dec 13, 2019 at 22:12

4 Answers 4

1

You have a better tool to store your users. Instead of an array (that forces you to know the length of the data loaded) you can use a List where you can add your elements while you read them.

Another point to change is the File.ReadAllText in File.ReadLines. This will allow to read line by line your file directly in the loop

public List<User> BuildUserList(string path)
{
    List<User> result = new List<User>();
    foreach (var record in File.ReadLines(path)
    {
        string[] data = record.Split(';'))
        User current = new User();
        current.ID = Convert.ToInt32(data[0]);
        current.Name = data[1];
        current.IsAdmin = Convert.ToBoolean(data[2]);
        result.Add(current);
    }
    return result;
}

Now you can use the list like an array if you need

List<User> users = BuildUserList("yourfile.txt");
if(users.Count > 0)
{
    Console.WriteLine("Name=" + users[0].Name);
}    
Sign up to request clarification or add additional context in comments.

Comments

0

If I were to assume your file especially each line having Id;Name;Admin values, I would write something like below to extract it. Please note that there are simple syntax out there but following logic will be helpful for beginners to understand how this could be achieved.

            List<User> userList = new List<User>();

            // Read the file located at c:\test.txt (this might be different in your case)
            System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
            string line;
            while ((line = file.ReadLine()) != null)
            {
                //following logic will read each line and split by the separator before
                // creating a new User instance. Remember to add more defensive logic to
                // cover all cases
                var extract = line.Split(';');
               userList.Add(new User()
               {
                   Id = extract[0],
                   Name = extract[1],
                   IsAdmin = extract[2]
               });
            }

            file.Close();

            //at this stage you will have List of User and converting it to array using following call

            var userArray = userList.ToArray();

Comments

0

And just as another variant, a linq-solution could look like this:

    var users = (
        from string line in System.IO.File.ReadAllLines(@"..filepath..")
        let parts = line.Split(';')
        where parts.Length == 3
        select new User() {
            ID = Convert.ToInt32(parts[0]),
            Name = parts[1],
            IsAdmin = Convert.ToBoolean(parts[2])}
            ).ToArray();

This can be elegant and short, error handling may be a bit more difficult.

Comments

0

This will read your file lazily, so it can handle extremely huge files with ease (assuming the rest of your code can):

public IEnumerable<User> ReadUsers(string path)
{
  return File.ReadLines(path)
    .Select(l=>l.Split(';'))
    .Select(l=> new User
    {
      Id = int.Parse(l[0]),
      Name = l[1],
      IsAdmin = bool.Parse(l[2])
    });
}

or

public IEnumerable<User> ReadUsers(string path)
{
  return File.ReadLines(path)
    .Select(l=>l.Split(';'))
    .Select(l=> new User(int.Parse(l[0]), l[1], bool.Parse(l[2])));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.