搜索用户变量的文本文件 - 这段代码出了什么问题

时间:2013-04-20 15:54:42

标签: c# file variables search text

尝试根据用户变量条目读取文本文件

我的条目有“Big Fred”这个名字的变体(大写/小写)

代码运行但我没有得到任何结果。

我的笔记本电脑上的代码指向我从下面的代码中删除的特定位置。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadTextFileWhile
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the name you wish to search for: ");                       //Prompt user for the name they wish to search for
            string x = Console.ReadLine();                                                      //assign the name the user inputs as their search parameter to the value of x
            StreamReader myReader = new StreamReader("C:/insert location here");      //Read the the text file at this location and assign to myReader
            string line = "";                                                                   //asssign 'nothing' to line.

            while (line != null)                                                                //while line in the text file is not null (empty)
            {
                line = myReader.ReadLine();                                                     //pass contents of myReader to line
                if (line != null && line == x)                                                  //if contents of line are not null and equal to the variable in x print to screen
                    Console.WriteLine(line);
            }

            myReader.Close();                                                                   //close myReader properly
            Console.ReadLine();                                                                 //Readline to keep console window open allowing a human to read output.

        }
    }
}

3 个答案:

答案 0 :(得分:1)

尝试使用string.IndexOf及其超出排除个案差异的重载

line = myReader.ReadLine();                                                     
if (line != null && line.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
      Console.WriteLine(line);

答案 1 :(得分:1)

你只想匹配字符串,以防敏感时尚正确。你可以使用.Equals

if (line.Equals(x,StringComparison.InvariantCultureIgnoreCase));

另一件事是: - 你可以使用

String.IsNullOrWhiteSpace(line) or String.IsNullOrEmpty(line) 

而不是检查是否为null

答案 2 :(得分:0)

您从文本文件中获取每一行的原因非常简单。您可能已经从网页或其他地方复制了文本内容。并且每一行都没有被新的行常量分隔\ n或Environment.NewLine。所以你需要的是打开文件和每行后按Enter键手动插入新行或从文件中读取所有测试并按Dot [。]分隔符拆分并使用上面的代码单独处理它。我遇到了同样的问题&现在它工作正常。