2011-02-01 7 views
5

Acabo de tener una función aquí que la persona que llama desea el número de bytes y luego devuelve los bytes, pero si no hay suficientes bytes en el archivo, debe devolver una matriz más pequeña. ¿Hay un mejor enfoque para hacer esto? Me refiero a no obtener 2 matriz y usar BlockCopy?¿Cómo obtener un mejor enfoque en la lectura de archivos?

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; 
    } 
} 

Respuesta

3

Simplemente actualice el recuento según la longitud del flujo para acortarlo si es necesario.

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; 
    } 
} 
+0

y ¿qué tal la parte que busca ?! –

+0

¡También utiliza 2 arrays y el método 'BlockCopy'! –

+1

Disculpa, solo se actualizó para tener en cuenta el desplazamiento. Solo usa 1 matriz y no usa la copia de bloques ... – Ian

0

Esto sólo asignar una matriz de bytes:

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; 
    } 
} 

Nótese, sin embargo, que de acuerdo a la documentación de MS en http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx, un FileStream en realidad podría leer menos bytes que hubieran solicitado, incluso si el final del hasn corriente se ha llegado.

Cuestiones relacionadas