开发者

How to obtain a better approach in reading file?

I just have a function here that caller wants number of bytes and then it returns the bytes but if there are not enough bytes in file it should return an smaller array. is there better approach to do this? I mean not getting 2 array 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,开发者_如何学Go 0, num);
        return tempdata;
    }
}


Just update the count based on the length of the stream to shorten 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;
    }
}


This will only allocate 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;
    }
}

Note, however, that according to MS documentation at http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx, a FileStream might actually read less bytes than requested even if the end of stream hasn't been reached.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜