2013-03-15 85 views
2

看到的分辨率的意见一条线 - 文件是放错了地方在循环使用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”。其他行被忽略。

请帮我看看这里。没有多个用户,我的程序是无用的。我到处寻找解决方案,包括本网站上的其他类似问题。从来没有想过从文件中读取会导致我浪费很多时间。

+1

@DGibbs有一个'while'各地它,没关系! – 2013-03-15 21:46:57

+3

您是否在调试器中检查过您的程序?看起来像一个调试问题...除此之外,如果不是明确地使用'StreamReader'使用''语句 – 2013-03-15 21:47:42

+0

您应该将'StreamReader reader = new StreamReader(“users.ul”);''然而,使用'声明,这个小小的改变不应该解决问题。您的问题可能与文件有关。用C#读取文件并不困难,除了缺少'using'语句外,你的代码是好的。 – evanmcdonnal 2013-03-15 21:50:35

回答

5

除非您特别需要使用StreamReader,否则我建议使用File.ReadAllLines(),它将返回一个(可枚举的)字符串数组。

更好

然而,使用LINQ :-)

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")) { 
    var lines = File.ReadAllLines("users.ul"); 
    // Usernames are listed first in users.ul, and are followed by a period 
    // and then the password associated with that username. 
    var users = lines.Select(o => o.Split('.')) 
        .Where(o => o.Length == 2) 
        .Select(o => new User(o[0].Trim(), o[1].Trim()); 

    System.Console.WriteLine("count: " + users.Count()); 
} 
+1

看到我上面的评论。我只是选择这个答案,所以我们不必等待8个小时来结束这个问题。感谢您的帮助!我可能会开始使用File方法 - 我是新来的C#。 – 2013-03-15 21:58:53

+0

听起来不错,我只为你写了一个很好的linq查询。 :-) – theMayer 2013-03-15 22:02:35

+0

我想知道为什么Linq在这里“更好”。我只通过阅读评论就能理解你的Linq查询。但我可以理解OP的代码。有光泽物体综合征的案例? – 2017-09-13 14:03:31

5

只是无法抗拒的诱惑,重构为一个班轮这一点:

var users = File.ReadAllLines("users.ul").Select(l => new User(l.Substring(0, l.IndexOf('.')), l.Substring(l.IndexOf('.') + 1))).ToDictionary(u => u.Name); 
+1

风格点数:-) – theMayer 2013-03-15 22:06:02

+4

你知道,程序员真的是艺术家,我们只是在不同的媒介工作。 – theMayer 2013-03-15 22:06:40