我只是在这里有一个函数,调用者想要字节数,然后它返回字节,但如果文件中没有足够的字节,它应该返回一个更小的数组.有没有更好的方法来做到这一点?我的意思是没有获得2个阵列并使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
只需根据流的长度更新计数即可在必要时缩短它。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |