在C#中搜索简单关键字的ASCII文件的最快方法?

Joa*_*nge 2 .net c# io performance

现在,我在ASCII文件中搜索简单的关键字,如下所示:

int SearchInFile (string file, string searchString)
{
    int num = 0;

    StreamReader reader = File.OpenText (file);
    string line = reader.ReadLine();

    while (line != null)
    {
        int count = CountSubstrings(line, searchString);
        if (count != 0)
        {
            num += count;
        }
        line = reader.ReadLine();
    }

    reader.Close();

    return num;
}
Run Code Online (Sandbox Code Playgroud)

这是最快,最有效的内存方式吗?返回计数是可选的,如果它将在搜索方式上产生巨大差异,但不是单独的.

我用它像:

SearchInFile ( "C:\\text.txt", "cool" );
Run Code Online (Sandbox Code Playgroud)

Ole*_*leg 5

在非托管代码中,性能方面最有效的方法是使用内存映射文件而不是在缓冲区中读取文件.我确信只有这样才能获得最佳结果,特别是如果您要扫描的文件可能是来自远程存储的文件(来自服务器的文件).

我不确定相应的.NET 4.0 类的使用是否与您的情况完全相同.