如何使我的文件读取类返回IEnumerable <byte []>对象</byte []>

时间:2010-07-01 19:08:11

标签: c# parallel-processing

...我可以读到BlockingCollection <byte[]&gt;与System.IO.File.ReadLines()可以读入BlockingCollection <string&gt;的方式相同在.net4.0?

3 个答案:

答案 0 :(得分:2)

您可以使用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();
}

答案 1 :(得分:1)

    public IEnumerable<Byte[]> ReadFile(String fileName)
    {
        using (FileStream file = new FileStream(fileName, FileMode.Open))
        {
            using (StreamReader reader = new StreamReader(file))
            {
                while (reader.Peek() >= 0)
                {
                    String line = reader.ReadLine();
                    yield return System.Text.Encoding.Default.GetBytes(line);
                }
            }
        }
    }

答案 2 :(得分:1)

听起来像“收益率回报”就是你要找的东西:

    static IEnumerable<byte> GetBytes()
    {
        byte[] bytes = new byte[10];
        // simple initialization of the array, replace with your I/O here if blocking
        for (byte x = 0; x < bytes.Length; x++)
        {
            bytes[x] = x;
        }
        // this generates the IEnumerable<byte>.
        // Replace "bytes[x]" with an I/O operation
        // that returns one byte if you want to allow data to flow as available through
        // the IEnumerable<byte>
        for (int x = 0; x < bytes.Length; x++)
        {
            yield return bytes[x];
        }
    }