看到的分辨率的意见一条线 - 文件是放错了地方在循环使用StreamReader.ReadLine只读取文本文件
我搜索一个答案所有的地方,但我没有能找到一个。这对我来说真是令人沮丧,因为我从来没有用任何其他编程语言从文件中读取这些麻烦。
我试图从基本即时消息程序的文本文件中提取用户名和密码。我不会发布所有的代码 - 它太长了,而且它很可能与程序开始时正在读取的文本文件不相关。
这里的文本文件的内容(“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”,密码为“passwor d”。其他行被忽略。
请帮我看看这里。没有多个用户,我的程序是无用的。我到处寻找解决方案,包括本网站上的其他类似问题。从来没有想过从文件中读取会导致我浪费很多时间。
@DGibbs有一个'while'各地它,没关系! – 2013-03-15 21:46:57
您是否在调试器中检查过您的程序?看起来像一个调试问题...除此之外,如果不是明确地使用'StreamReader'使用''语句 – 2013-03-15 21:47:42
您应该将'StreamReader reader = new StreamReader(“users.ul”);''然而,使用'声明,这个小小的改变不应该解决问题。您的问题可能与文件有关。用C#读取文件并不困难,除了缺少'using'语句外,你的代码是好的。 – evanmcdonnal 2013-03-15 21:50:35