473,396 Members | 1,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

MemoryStreams/BinaryReader/BinaryWriter

I'm writing from a serial port into a MemoryStream via a BinaryWriter in my
protocol object.
After I've filled the memorystream, which is approx 200KB in size, I then
pass it up to my datahandler object where I plan to create a BinaryReader to
extract the data and format it ready for a database insert.
At the moment I close the binarywriter earlier than my call to the
datahandler object, and Ive just found out that closing the binarywriter
also closes the memorystream so that it's no longer available.
What's the best/nicest way to do this? Can I attach more than 1
reader/writer to a memorystream at the same time?
Nov 16 '05 #1
1 6200
Claire <bl****@blahhhhh.com> wrote:
I'm writing from a serial port into a MemoryStream via a BinaryWriter in my
protocol object.
After I've filled the memorystream, which is approx 200KB in size, I then
pass it up to my datahandler object where I plan to create a BinaryReader to
extract the data and format it ready for a database insert.
At the moment I close the binarywriter earlier than my call to the
datahandler object, and Ive just found out that closing the binarywriter
also closes the memorystream so that it's no longer available.
What's the best/nicest way to do this? Can I attach more than 1
reader/writer to a memorystream at the same time?


I have a nasty solution for you - insert a NonClosingProxyStream (or
some similarly named class) in between. This class would proxy all the
stream methods *except* Close/Dispose to whatever stream it's
constructed with. Instead of wrapping the MemoryStream directly in a
BinaryWriter, you wrap it in a NonClosingProxyStream and then wrap the
BinaryWriter round that.

Here's an example of such a class - warning, I haven't tested it
properly as it's part of something else I'm writing but haven't looked
at for a while:

using System;
using System.IO;
using System.Threading;
using System.Runtime.Remoting;

namespace MiscUtil.IO
{
/// <summary>
/// Wraps a stream for all operations except Close and Dispose,
/// which merely flush the stream and prevent further operations
/// from being carried out using this wrapper.
/// </summary>
public sealed class NonClosingStreamWrapper : Stream
{
#region Members specific to this wrapper class
public NonClosingStreamWrapper(Stream stream)
{
this.stream = stream;
}

Stream stream;
/// <summary>
/// Stream wrapped by this wrapper
/// </summary>
public Stream BaseStream
{
get { return stream; }
}

/// <summary>
/// Whether this stream has been closed or not
/// </summary>
bool closed=false;

/// <summary>
/// Throws an InvalidOperationException if the wrapper is
/// closed.
/// </summary>
void CheckClosed()
{
if (closed)
{
throw new InvalidOperationException
("Wrapper has been closed or disposed");
}
}
#endregion

#region Overrides of Stream methods and properties
public override IAsyncResult BeginRead
(byte[] buffer, int offset, int count,
AsyncCallback callback, object state)
{
CheckClosed();
return stream.BeginRead (buffer, offset,
count, callback, state);
}

public override IAsyncResult BeginWrite
(byte[] buffer, int offset, int count,
AsyncCallback callback, object state)
{
CheckClosed();
return stream.BeginWrite
(buffer, offset, count, callback, state);
}

public override bool CanRead
{
get { return closed ? false : stream.CanRead; }
}

public override bool CanSeek
{
get { return closed ? false : stream.CanSeek; }
}

public override bool CanWrite
{
get { return closed ? false : stream.CanWrite; }
}

/// <summary>
/// This method is not proxied to the underlying stream;
/// instead, the wrapper
/// is marked as unusable for other (non-close/Dispose)
/// operations. The underlying
/// stream is flushed if the wrapper wasn't closed before
/// this call.
/// </summary>
public override void Close()
{
if (!closed)
{
stream.Flush();
}
closed = true;
}

public override ObjRef CreateObjRef(Type requestedType)
{
throw new NotSupportedException();
}

public override int EndRead(IAsyncResult asyncResult)
{
CheckClosed();
return stream.EndRead (asyncResult);
}

public override void EndWrite(IAsyncResult asyncResult)
{
CheckClosed();
stream.EndWrite (asyncResult);
}

public override void Flush()
{
CheckClosed();
stream.Flush();
}

public override object InitializeLifetimeService()
{
throw new NotSupportedException();
}

public override long Length
{
get
{
CheckClosed();
return stream.Length;
}
}

public override long Position
{
get
{
CheckClosed();
return stream.Position;
}
set
{
CheckClosed();
stream.Position = value;
}
}

public override int Read(byte[] buffer, int offset,
int count)
{
CheckClosed();
return stream.Read(buffer, offset, count);
}

public override int ReadByte()
{
CheckClosed();
return stream.ReadByte();
}

public override long Seek(long offset, SeekOrigin origin)
{
CheckClosed();
return stream.Seek(offset, origin);
}

public override void SetLength(long value)
{
CheckClosed();
stream.SetLength(value);
}

public override void Write(byte[] buffer, int offset,
int count)
{
CheckClosed();
stream.Write(buffer, offset, count);
}

public override void WriteByte(byte value)
{
CheckClosed();
stream.WriteByte(value);
}
#endregion
}
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Mark Miller | last post by:
I have a char array and when I write it to a file using BinaryWriter the position of the pointer is the size of the array + 1. For example: writing char leaves the pointer at position 26 after...
2
by: Chris P. | last post by:
I have a C# application that connects to Perl application on a UNIX server. I am able to connect and communicate both directions with the server, but there are several occasions when it appears...
0
by: Denny Rue | last post by:
I’ve created VB code to download files from a web site through the use of HTTPWebRequest, HTTPWebResponse and BinaryReader. The HTTPWebRequest has a TimeOut property to limit how long it waits...
6
by: ThunderMusic | last post by:
Hi, In my app, I open a file using a FileStream then pass it to a BinaryWriter. I then use the BinaryWriter instance to write to my file. But a problem arose : The file never gets bigger than 1kb....
3
by: liljester | last post by:
Is there a way to tell this method how many bytes to read from the stream? the msdn documentation doesnt explain its usage very well... Any help would be much appreciated
2
by: Bob Rock | last post by:
I already found an alternative way to accomplish this (using ReadBytes), still I'd like to understand why I'm getting and error reading a text file using the following method. The exception is...
4
by: Paul Steele | last post by:
I am writing a client/server application that communicates over tcp. The code I use to initiate the connection is as follows: NetworkStream networkStream = new NetworkStream(ClientSocket);...
6
by: Question with BinaryReader | last post by:
I use BinaryReader to read my binary dafa files, when i call ReadBytes, why it always return more 4 bytes. The following is my code. FileStream fs = new FileStream(file, FileMode.OpenOrCreate,...
3
by: Eugene | last post by:
I'm trying to write a class which uses BinaryWriter as its base but allows for queuing of write requests Public Class QueuedBinaryWriter Inherits BinaryWriter I override all the Write methods...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.