How to get a better approach in a reading file?

I have a function here when the caller wants the number of bytes and then returns the bytes, but if there are not enough bytes in the file, it should return a smaller array. is there a better approach for this? I mean do not get 2 arrays and use BlockCopy?

byte[] GetPartialPackage(string filePath, long offset, int count)
{
    using (var reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        reader.Seek(offset, SeekOrigin.Begin);
        byte[] tempData = new byte[count];
        int num = reader.Read(tempData, 0, count);
        byte[] tempdata = new byte[num];
        Buffer.BlockCopy(tempData, 0, tempdata, 0, num);
        return tempdata;
    }
}
+5
source share
2 answers

Just update the bill depending on the length of the stream to reduce it if necessary.

byte[] GetPartialPackage(string filePath, long offset, int count)
{
    using (var reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        reader.Seek(offset, SeekOrigin.Begin);
        int avaliableCount = Math.Min(count, (int)(reader.Length - offset));
        byte[] tempData = new byte[avaliableCount];
        int num = reader.Read(tempData, 0, avaliableCount);
        return tempData;
    }
}
+3
source

This will allocate only one byte array:

byte[] GetPartialPackage(string filePath, long offset, int count)
{
    using (var reader = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        reader.Seek(offset, SeekOrigin.Begin);
        int actualCount = Math.Min(count, reader.Length - offset);
        byte[] tempData = new byte[actualCount];
        reader.Read(tempData, 0, actualCount);        
        return tempdata;
    }
}

, , MS http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx, FileStream , , .

0