简体   繁体   中英

C# can't split a string into an array by newline (from StreamReader)

StreamReader login = new StreamReader("C:/Users/Me/Documents/logins.txt");
            string ar = login.ReadToEnd();
            string[] names = ar.Split("\r\n");
login.Close();

I'm reading from a file a set of logins, exampled as "username,password" then a newline as "usr,pwd" or something else. I want to split the txt file into a set of arrays by splitting at the start of a new line, but "\\r\\n" doesn't seem to be working, coming up with the error "cannot convert from string to char". I have tried Environment.Newline, but that is not working either, coming with the same error message.

而不是处理流只需使用File.ReadAllLines

string[] names = File.ReadAllLines("C:/Users/Me/Documents/logins.txt");

String.Split needs an array or eiter char or string values to split on. You need to change your code to:

string[] names = ar.Split(new string[]{"\r\n"}, StringSplitOptions.None);

You can read each line individually like so:

using (StreamReader reader = new StreamReader(pathToFile)) {
    string line = reader.ReadLine();
}

This may be preferable as you don't have to rely on the line return type to be correct using a char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM