StreamReader无法在文件中查找字符串

时间:2017-03-23 14:26:14

标签: c# winforms visual-studio-2015 streamreader

我遇到了SteamReader的问题。我的StreamReader在文件中找不到特定的字符串匹配,即使我知道该字符串存在。显示这一点的最佳方式是通过图像。您将更好地了解它的工作原理。我将提供以下代码: enter image description here

图像显示了检查字符串是否在文件中的代码。打开的文本文档是检查的文件。当输入信息后创建新表单(此表单)时,它将作为变量传递。表单按钮是运行代码的按钮,如图所示。如果找不到该字符串,则会显示消息框。

正如您所看到的那样,该文件包含了该字符串,但根本没有将其取出:/

我怀疑这很简单,但我需要一双新鲜的眼睛。这是代码:

private void btnGetActivities_Click(object sender, EventArgs e)
    {
        if (File.Exists(sVenueName.ToString() + ".txt"))
        {
            using (StreamReader RetrieveEvents = new StreamReader(sVenueName.ToString() + ".txt"))                    //Create a new file with the name of the username variable
            {
                string EventString;
                string EventType;
                string EventPeopleAttending;
                string line = RetrieveEvents.ReadLine();                                        //Declare string variable to hold each line in the file

                while (RetrieveEvents.Peek() != -1)
                {


                    if (line.Contains("Event Name:")) //When this line is found,
                    {
                        EventString = line.Remove(0, 12);                         //Remove the characters from the line and store it in a variable
                        lstDisplayActivities.Items.Add(line);

                        line.Skip(1).Take(2);
                        EventType = line.Remove(0, 12);
                        lstDisplayActivities.Items.Add(line);

                        line.Skip(2).Take(3);
                        EventPeopleAttending = line.Remove(0, 18);
                        lstDisplayActivities.Items.Add(line);
                    }
                    else
                    {
                        MessageBox.Show("No Files were found");
                    }
                }
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

您只读取StreamReader中的第一行。其他行永远不会读。你需要一个循环,并在每个循环再次读取一行

 line.Skip(1).Take(2) 

<div *ngFor='let project of projectsArray.projects'>
    {{project.name}}
    {{project.activity}}
</div>

并且喜欢没有前进到下一行,但是他们只是跳过第(1)行中的字符数,然后取下以下2个字符只是为了丢弃你没有把它分配给任何东西的所有内容

答案 1 :(得分:0)

详细说明@CNuts在评论中所说的内容

if (line.Contains("Event Name:")) //When this line is found,
{
     //Do stuff
}
else
{
    MessageBox.Show("No Files were found");
}

由于并非文件中的所有行都包含“事件名称:”,每次该行不包含此特定字符串时,您将收到消息“未找到文件”。

这是一个建议:

bool eventsFound = false
while (RetrieveEvents.Peek() != -1)
{
    if (line.Contains("Event Name:")) //When this line is found,
    {
        //Do stuff
        eventsFound = true;
    }
    line = RetrieveEvents.ReadLine();
}
if(!eventsFound)
    MessageBox.Show("No Files were found");