Read/Write Streams
To utilize the API, include the following namespace in your application:
Alachisoft.NCache.Web.Caching.
GetCacheStream
API with different overloads is used to open a stream. GetCacheStream
API
opens the stream of specified key with provided streaming mode. It returns the
handle of the opened stream as an object of CacheStream
class.
CacheStream
is derived from System.IO.Stream
. It is designed to read/write
BLOB using standard Stream interface. However, it does not support 'seeking'
which is the querying and modifying the current position within a stream.
Reading from Stream
This mode is used for acquiring read-only access to the stream. With the help of the example given below, a stream can be opened with read-only property on provided key.
string key = "key:ncache-guide";
CacheStream cacheStream = null;
try
{
cacheStream = cache.GetCacheStream(key, StreamMode.Read);
}
catch (StreamException ex)
{
// handle exception
}
Now data can be read from this CacheStream
object. GetCacheStream
with Read
mode throws StreamException if no data exists in the cache with the specified
key.
Reading from Stream without Lock
This mode is useful when write and read operations are to be performed in parallel. The following example explains how to get stream object with read-without-lock property.
string key = "key:ncache-guide";
CacheStream cacheStream = null;
try
{
cacheStream = cache.GetCacheStream(key, StreamMode.ReadWithoutLock);
}
catch (StreamException ex)
{
// handle exception
}
Data can be read from this CacheStream object. GetCacheStream
with
ReadWithoutLock
mode throws StreamException
if no data exists in the cache
with the specified key.
Writing to a Stream
In write mode only a single write operation can be performed on a stream. It will throw an exception if stream is already in use by another application.
string key = "key:ncache-guide";
CacheStream cacheStream = null;
try
{
cacheStream = cache.GetCacheStream(key, StreamMode.Write);
}
catch (OperationFailedException ex)
{
// handle exception
}
Now data can be written to this CacheStream
object.
Using GetBufferedStream
Buffered stream is the set of bytes used for storing the data up to the certain
limit before reading or writing it to the cache. The following code shows how to
use GetBufferedStream
:
string key = "key:ncache-guide";
byte[] writeBuffer = System.IO.File.ReadAllBytes("C:\\ncache-manual.pdf");
int length = writeBuffer.Length;
try
{
System.IO.Stream wstream = cache.GetCacheStream(key, StreamMode.Write).GetBufferedStream(length);
//...No data is written in cache as buffer is not full
wstream.Write(writeBuffer, 0, length/2);
//...Data is written in cache because buffer is full now
wstream.Write(writeBuffer, length/2, length/2);
//...Close the stream
}
catch (StreamException ex)
{
// handle exception
}