c# – 在循环中使用StreamReader.ReadLine只从文本文件中读取一
发布时间:2020-12-16 00:22:34 所属栏目:百科 来源:网络整理
导读:看到解决方案的评论 – 文件在错误的地方 我到处寻找答案,但我找不到答案.这对我来说真的很令人沮丧,因为我从来没有从使用任何其他编程语言的文件中读取这么多麻烦. 我正在尝试从文本文件中提取用户名和密码,以获得基本的即时消息程序.我不打算发布所有代码
看到解决方案的评论 – 文件在错误的地方
我到处寻找答案,但我找不到答案.这对我来说真的很令人沮丧,因为我从来没有从使用任何其他编程语言的文件中读取这么多麻烦. 我正在尝试从文本文件中提取用户名和密码,以获得基本的即时消息程序.我不打算发布所有代码 – 它太长了,而且很可能不相关,因为文本文件是在程序的最开始读取的. 这是我试图读取的文本文件(“users.ul”)的内容: admin.password billy.bob sally.sal 以下是从文本文件中读取的代码: users = new Dictionary<string,User>(); System.Console.WriteLine("users.ul exists: " + File.Exists("users.ul")); // Check the status of users.ul. If it exists,fill the user dictionary with its data. if (File.Exists("users.ul")) { // Usernames are listed first in users.ul,and are followed by a period and then the password associated with that username. StreamReader reader = new StreamReader("users.ul"); string line; int count = 0; while ((line = reader.ReadLine()) != null) { string[] splitted = line.Split('.'); string un = splitted[0].Trim(); string pass = splitted[1].Trim(); User u = new User(un,pass); // Add the username and User object to the dictionary users.Add(un,u); count++; } System.Console.WriteLine("count: " + count); reader.Close(); } 这是我的代码产生的输出: users.ul exists: True count: 1 添加到用户词典的唯一数据是“admin”,密码为“password”.其他行被忽略. 请帮帮我.没有多个用户,我的程序没用.我到处寻找解决方案,包括本网站上的其他类似问题.从没想过从文件中读取会让我浪费那么多时间. 解决方法
除非您特别需要经历使用StreamReader的严格要求,否则我建议使用
File.ReadAllLines() ,它返回一个(可枚举的)字符串数组.
更好的是,使用linq (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |