The size of buffer

A

ad

I new a buffer for read file:
How to detriminate the BolockSize when new the buffer?


-----------------------------------------------------------------------------------------------------------------------------------------
int BlockSize=????
System.IO.FileStream fsRead = new System.IO.FileStream("c:\Backup.bck",
System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] buffer = new byte[BlockSize];
System.Int32 size = fsRead.Read(buffer, 0, buffer.Length);
 
G

Guest

Hi ad,
generally when you do not know the size of the file in advance, you can
just assign some arbritary size to your buffer and keep looking in a while
loop calling read until the FileStream.Read function returns a value < 0 at
which point you know there is no more data.

In the code example you gave, you know exactly the size of the file you are
reading because you can use the FileInfo object to get the size of the file
in bytes i.e.

System.IO.FileInfo fi = new FileInfo(@"c:\backup.bck");
long fileSize = fi.Length;

I would not make your buffer equal to the size of your file though, make it
some arbitrary size like 500K, for example, and keep looping until all the
data is read, this way if you are reading a large file or you want to cancel
the operation you still have chance to cancel the read operation by putting
extra code in your while loop to do so i.e.

System.IO.FileInfo fi = new FileInfo(@"c:\backup.bck");
long fileSize = fi.Length;

//have some boolean that can be set i.e. when the user clicks on
//a cancel button this would turn to false
bool keepReading = true;

byte[] arrData = new byte[500 * 1024];

long remainingData = fileSize;
int dataRead;
int offset = 0;

while(remainingData > 0 && keepReading)
{
dataRead = fs.Read(arrData, offset, remainingData);

if(dataRead <= 0)
{
//we are done
break;
}

remainingData -= dataRead;
}

Hope that helps
Mark R Dawson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top