在C#中读取具有未知位置的特定行

时间:2015-11-26 07:52:08

标签: c# wpf streamreader

我正在尝试编写程序来从.txt文件中读出用户组并将所述组放入列表框中。组列表的示例如下:

用户

-------------

组别1

组2

第3组

[空格]

[空格]

下一位用户

每个用户都有未知数量的群组,这就是为什么有两个空格,只是为了分隔所有内容。

到目前为止,我的进展如下:

 private void Button_Click(object sender, RoutedEventArgs e) {
        //users.txt contains all users
        //in the same directory there are multiple lists with given groups
        StreamReader sr = new StreamReader("c:\\ADHistory\\users.txt", System.Text.Encoding.Default);
        string line = string.Empty;
        try {
            //Read the first line of text
            line = sr.ReadLine();
            //Continue to read until you reach end of file
            while (line != null) {
                listboxNames.Items.Add(line);
                //Read the next line
                line = sr.ReadLine();
            }

            //close the file
            sr.Close();
        }
        catch (Exception f)
        {
            MessageBox.Show(f.Message.ToString());
        }
        finally
        {
            //close the file
            sr.Close();
        }
    }

    private void listboxNames_SelectionChanged(object sender, SelectionChangedEventArgs e) {
        //as soon as you choose a user from the first list
        //you may choose a date to look at all groups the user is in.
        listboxDates.Items.Clear();
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\ADHistory");
        FileInfo[] Files = dinfo.GetFiles("*.txt");

        //this adds all dates into the second listbox
        //and removes users.txt from the list.
        foreach (FileInfo file in Files) {
            listboxDates.Items.Add(file.Name);
        }
        for (int n = listboxDates.Items.Count - 1; n >= 0; --n)
        {
            string removelistitem = "users";
            if (listboxDates.Items[n].ToString().Contains(removelistitem))
            {
                listboxDates.Items.RemoveAt(n);
            }
            //this displays the user below the listboxes,
            //because of styling purposes
            string user = Convert.ToString(this.listboxNames.SelectedItem);
            labelName.Content = user;

        }
    }

    //here we have my main problem.
    //I can't find a solution to add the groups to the last listbox
    private void listboxDates_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string user = Convert.ToString(labelName.Content);
        listboxGroups.Items.Clear();
        string path = "C:\\ADHistory\\";
        path += Convert.ToString(this.listboxDates.SelectedItem);

        foreach (string line in File.ReadLines(path))
        {
            if (line.Contains(user))
            {
                while (line != " ")
                {
                    listboxGroups.Items.Add(line);
                }
            }
        }
    }

我真的希望你能帮助我。

修改

此问题已得到解答,因此无需回答。 感谢所有评论:)

1 个答案:

答案 0 :(得分:1)

你的问题是,当找到用户的行时,你测试行==" "没有前进到下一个,你的while循环应立即退出

使用for循环而不是每个循环。当你发现用户行相同的时候有你的while循环,并在while循环中用++增加循环变量并读取下一行。在设置line = fileLines [lineIndex]

之前不要忘记检查字符串数组长度

因此,以下是应该适合您的代码

string[] fileLines = File.ReadAllLines(path);

for (int lineIndex = 0; lineIndex < fileLines.Length; lineIndex++)
{
    string line = fileLines[lineIndex];
    if (line.Contains(user))
    {
        while(++lineIndex < fileLines.Length && (line = fileLines[lineIndex]) != " ")
        {
            listboxGroups.Items.Add(line);
        }
        break;
    }
}

但是,如果文件很大,你可能不希望将所有内容读入内存,这是另一种适用于File.ReadLines()的方法

IEnumerator<string> fileLines = File.ReadLines(path).GetEnumerator();

while (fileLines.MoveNext())
{
    string line = fileLines.Current;
    if (line.Contains(user))
    {
        while (fileLines.MoveNext())
        {
            line = fileLines.Current;
            if (line == " ")
            {
                break;
            }
            listboxGroups.Items.Add(line);
        }
        break;
    }
}