Im writing a small web application and what I'd like to do is open a
file, read the contents into memory and then close the file as fast as
I can to free up the file for the next user. Once the file is loaded
into memory and subsequently closed, i would use the contents of the
file (now loaded into memory) to perform some quick processing. Any
idea how best to do this?
Assuming your files are small enough to easily fit in memory, it seems to
me that you could just check the file size, allocate a byte array long
enough to hold the data, then open the file with FileStream, read the
entire file into the byte array in a single call to FileStream.Read(), and
then close the file.
Caveat: a FileStream implementation is not actually required to read as
many bytes as you ask it to. So you should put the call to Read() into a
loop, iteratively reading whatever it will allow you to until it's all
done. For example:
byte[] rgb = ...;
using (FileStream stream = ...)
{
int cbLeft = stream.Length;
while (cbLeft > 0)
{
cbLeft -= stream.Read(rgb, stream.Length - cbLeft, cbLeft);
}
}
In most cases, I believe that Read() will only be called once and it will
read the entire file in one shot. But this will handle those cases when,
for whatever reason, you don't get all the data the first call to Read().
Depending on how you're going to use the data, you can then optionally
instantiate a MemoryStream from the byte array, so that you still have
stream-based access to the data (which you could then pass to a
StreamReader, for example, if you wanted to process text).
Pete
Using a filestream has another advantage, you can open it
readonly/share-read so that other processes can also open it the same way,
making the locking issue completely go away.
Mike.