在C#中搜索文本文件中的单词失败

时间:2017-04-05 08:51:31

标签: c# .net streamreader

请查看以下代码。

DirectoryInfo directory = new DirectoryInfo(@"XXXXXX   \IN");
FileInfo[] files = directory.GetFiles("*.*");

     foreach (var f in files)   //FETCHING FILES FROM THE BULK FOLDER (IN)
        {
            string path_f = f.FullName;
            StreamReader myfile = new StreamReader(path_f);                    
            StreamReader basis = new StreamReader(@"C:XXXXXXXX\SCH.TXT");

               while (basis.EndOfStream == false)
                        {
                            string canon = basis.ReadLine();  //CANON STORES EACH WORD FROM SCH.TXT
                            canon = canon.Trim();

                            while (myfile.EndOfStream == false)
                            {
                                string line = myfile.ReadLine();
                                if (line.Contains(canon))
                                DISCH_COUNT++;


                            } // END OF WHILE

                         } // END OF WHILE

                    basis.Close();               

            } 

        myfile.close();

SCH.TXT包含一些单词。我需要搜索这些单词出现在文件中的次数。我从SCH.txt中获取每个单词并在文件中搜索。我的问题是第一个单词,搜索是完成的。从第二个单词开始,条件myfile.EndOfStream == false正在失败。你能帮我解决这个问题吗?? ??

1 个答案:

答案 0 :(得分:0)

尝试这样逐行阅读文本内容

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}

file.Close();

我没有测试代码,但它会为您提供基本的想法,即如何实现搜索功能。祝你好运