...我可以将System.IO.File.ReadLines()读入.net4.0中的BlockingCollection >中的方式读取到BlockingCollection >中?

最佳答案

您可以使用File.Open来获取FileStream,然后使用FileStream.Read:

IEnumerable<byte[]> GetFileBytes(string filename)
{
    var fsSource = File.Open(filename, FileMode.Open);
    const int bytesToReadPerIteration = 100;
    int numBytesToRead = (int)fsSource.Length;
    int numBytesRead = 0;
    while (numBytesToRead > 0)
    {
        byte[] bytes = new byte[Math.Min(bytesToReadPerIteration, numBytesToRead)];
        // Read may return anything from 0 to numBytesToRead.
        int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

        // Break when the end of the file is reached.
        if (n == 0)
            break;

        if (n != bytes.Length)
        {
             byte[] tmp = new byte[n];
             Array.Copy(bytes, tmp, n);
             bytes = tmp;
        }

        yield return bytes;

        numBytesRead += n;
        numBytesToRead -= n;
    }

    fsSource.Close();
}

关于c# - 如何使我的文件读取类返回IEnumerable <byte []>对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3160907/

10-11 09:00