The quick, inefficient answer to your question is that you could add the following within your for loop beneath the int b = fs.ReadByte();
line:
// b will be -1 if the end of the file is reached
if (b >= 0)
{
arrfile[i] = (byte)b;
}
However, I'd suggest using the Read
method to read all of the bytes into your array. Once you have them loaded into memory, you can manipulate the data in the array however you need to. Below is your code revised to use that approach:
using(FileStream fs = new FileStream(@strWAVEPath, FileMode.Open, FileAccess.Read))
{
byte[] arrfile = new byte[fs.Length - 44];
fs.Position = 4;
int remainder = arrfile.Length;
int startIndex = 0;
int read;
do
{
read = fs.Read(arrfile, startIndex, remainder);
startIndex += read;
remainder -= read;
} while (remainder > 0 && read > 0);
return arrfile;
}
The reason for the while loop is that the Read
method is not guaranteed to read all of the bytes that you request it to read on the first try. It will read at least one byte and not more than the number of bytes that you specify in the third parameter, unless it is at the end of the stream, in which case it will read zero bytes.
Also note that I put a using statement around your FileStream
. You were calling the Close
method on the FileStream
, which was good, except that it wouldn't be called if an exception were thrown before reaching that point. The using statement effectively does the same thing, but will make sure the stream is closed even if an exception is thrown.