E
E
eskims2021-09-07 20:21:45
C++ / C#
eskims, 2021-09-07 20:21:45

How to properly split lines?

There is a code:

c# code
string[] data = File.ReadAllText(OFD.FileName).Split( ':' );
            for (int i = 0; i < data.Length - 1; i+=2)
            {
                logins.Add(data[i]);
                pass.Add(data[i+1]);

            }

And the text file path to which in OFD.FileName contains lines in the format:
.txt
log:pass
log1:pass1


So, with further use of this data, it turns out that I cannot adequately use the line after the ":", because it gives the error "Object reference not set to an instance of an object."

Can you suggest what is wrong here?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-08
@eskims

It is difficult to say where NRE comes from, as the code, although scary, is working.
An error can occur if OFD, OFD.FileName, logins, or pass is null.
A little advice on how to improve the code:
1. We make a separate type for the login-password pair, and use one list for this
2. We read the file not entirely, but line by line.

var path = "...";
var lines = await File.ReadAllLinesAsync(path);
var allCredentials = lines.Select(Credentials.Parse).ToList();

public record Credentials(string Username, string Password) {
  public static Credentials Parse(string line) {
      var parts = line.Split(':');
      return new(parts[0], parts[1]);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question