在参考了很多博客和文章之后,我已经达到了以下代码,用于在文件夹内的所有文件中搜索字符串.它在我的测试中运行良好.
质询
注意:我测试了非常小的文件.文件数量也很少.
码
static void Main()
{
string sourceFolder = @"C:\Test";
string searchWord = ".class1";
List<string> allFiles = new List<string>();
AddFileNamesToList(sourceFolder, allFiles);
foreach (string fileName in allFiles)
{
string contents = File.ReadAllText(fileName);
if (contents.Contains(searchWord))
{
Console.WriteLine(fileName);
}
}
Console.WriteLine(" ");
System.Console.ReadKey();
}
public static void AddFileNamesToList(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
allFiles.Add(fileName);
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points" …Run Code Online (Sandbox Code Playgroud) 我现在正在研究字符串搜索算法,并想知道.NET String.Contains函数用于什么算法.Reflector显示使用了这个函数,但我不知道它的名字是什么意思.
private static extern int InternalFindNLSStringEx(IntPtr handle, string localeName, int flags, string source, int sourceCount, int startIndex, string target, int targetCount);
Run Code Online (Sandbox Code Playgroud) 这是我对BMH算法的实现(它就像一个魅力):
public static Int64 IndexOf(this Byte[] value, Byte[] pattern)
{
if (value == null)
throw new ArgumentNullException("value");
if (pattern == null)
throw new ArgumentNullException("pattern");
Int64 valueLength = value.LongLength;
Int64 patternLength = pattern.LongLength;
if ((valueLength == 0) || (patternLength == 0) || (patternLength > valueLength))
return -1;
Int64[] badCharacters = new Int64[256];
for (Int64 i = 0; i < 256; ++i)
badCharacters[i] = patternLength;
Int64 lastPatternByte = patternLength - 1;
for (Int64 i = 0; i < lastPatternByte; ++i)
badCharacters[pattern[i]] = …Run Code Online (Sandbox Code Playgroud)