File Search in C#
<p>I have made this code:</p>

<pre><code>string[] paths = GetFiles(dir).ToArray();

int numberOfFiles = paths.Length;
int i = 0;
while (i &lt; numberOfFiles - 1)
{
    scanfile(paths[i]);
    i++;
}
</code></pre>

<p>And for the GetFiles:</p>

<pre><code>static IEnumerable&lt;string&gt; GetFiles(string path) {
Queue&lt;string&gt; queue = new Queue&lt;string&gt;();
queue.Enqueue(path);
while (queue.Count &gt; 0)
{
    path = queue.Dequeue();
    try
    {
        foreach (string subDir in Directory.GetDirectories(path))
        {
            queue.Enqueue(subDir);
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex);
    }
    string[] files = null;
    try
    {
        files = Directory.GetFiles(path);
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex);
    }
    if (files != null)
    {
        for (int i = 0; i &lt; files.Length; i++)
        {
            yield return files[i];
        }
    }
}
}

public string scanfile(string path)
    {
        int offset = 0;
        int length = 0;
        byte[] buffer;
        var variable1 = new StringBuilder();

        FileInfo fi = new FileInfo(path);
        length = (int)fi.Length;


            using (var mmf1 = MemoryMappedFile.CreateFromFile(path,
                FileMode.OpenOrCreate, null, offset + length))
            {
                // Create reader to MMF
                using (var reader = mmf1.CreateViewAccessor(300,
                4000, MemoryMappedFileAccess.Read))
                {
                    // Read from MMF
                    buffer = new byte[4000];
                    reader.ReadArray&lt;byte&gt;(0, buffer, 0, 4000);
                }
            }

        return variable1.ToString();

    }
</code></pre>

<p>P.S.: Get Files I took it from Stack Overflow too.</p>

<p>But, it's very slow if i use it for many files in a directory because it
calculates first the files in the directory. </p>

<p>Can you help me to optimize these codes? </p>
