我正在尝试创建一个搜索文件的应用程序,就像 WindowsXP 一样。我正在使用 4 个线程搜索指定目录并打开每个文件以搜索字符串。这是通过从静态类调用静态方法来完成的。然后该方法尝试找出扩展,并根据找到的扩展通过私有方法运行它。我只创造了将纯文本文件读取到班级的可能性。这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Searcher
{
static public class Searching
{
static public bool Query(string file, string q)
{
file = file.ToLower();
if (file.EndsWith(".txt")) // plain textfiles
{
return txt(file, q);
} // #####################################
else if (file.EndsWith(".doc"))
{
return false;
} // #####################################
else if (file.EndsWith(".dll")) // Ignore these
{
return false;
}
else if (file.EndsWith(".exe")) // Ignore these
{
return false;
}
else // will try reading as a textfile
{
return txt(file, q);
}
}
static private bool txt(string file, string q)
{
string contents;
TextReader read = new StreamReader(file);
contents = read.ReadToEnd();
read.Dispose();
read.Close();
return contents.ToLower().Contains(q);
}
static private bool docx(string file, string q)
{
return false;
}
}
}
Query 读取扩展名,然后转发处理。由于此时我只包含纯文本文件,因此无法选择太多。在搜索开始之前,我还告诉我的程序它需要读取所有可能的文件。
现在我的问题出在这里,虽然阅读器只能阅读纯文本文件,但它也可以阅读图像和应用程序(.exe/.dll)。这是意料之中的,因为它试图读取所有内容。奇怪的是,它返回匹配项。我已经在 Notepad++ 中搜索了文件,但没有匹配项。我还在文件被读入“内容”变量后立即使用断点提取了内容,并尝试搜索该内容,但再次没有匹配。所以这意味着 String.Contains() 方法不能很好地搜索内容,这似乎认为给定的查询在文件中。
我希望有人知道问题可能是什么。我搜索的字符串是“test”,该程序在搜索文本文件时工作。