473,657 Members | 2,587 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6235
Claire <bl****@blahhhh h.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 NonClosingProxy Stream (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 NonClosingProxy Stream 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.Threadin g;
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 NonClosingStrea mWrapper : Stream
{
#region Members specific to this wrapper class
public NonClosingStrea mWrapper(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 InvalidOperatio nException if the wrapper is
/// closed.
/// </summary>
void CheckClosed()
{
if (closed)
{
throw new InvalidOperatio nException
("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.BeginRea d (buffer, offset,
count, callback, state);
}

public override IAsyncResult BeginWrite
(byte[] buffer, int offset, int count,
AsyncCallback callback, object state)
{
CheckClosed();
return stream.BeginWri te
(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(Ty pe requestedType)
{
throw new NotSupportedExc eption();
}

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

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

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

public override object InitializeLifet imeService()
{
throw new NotSupportedExc eption();
}

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(buf fer, offset, count);
}

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

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

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

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

public override void WriteByte(byte value)
{
CheckClosed();
stream.WriteByt e(value);
}
#endregion
}
}
--
Jon Skeet - <sk***@pobox.co m>
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
5135
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 starting at position 0. I thought that char was 2 bytes, but this makes it seem as though it is just 1 when I write to a file. Why is this? I imagine the extra bit is just a null bit (correct me if I'm wrong). I don't know if this helps but when I...
2
2432
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 that the BinaryReader only reads part of the message sent by the server. Here is the main flow of my application. 1. Open Socket 2. Read 4 byte integer 3. Read byte array that is the size of the integer in step 2. 4. Put message in collection
0
2107
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 for a corresponding HTTPWebResponse. This works just fine. However, the timeout does not appear to apply to a BinaryReader created from the HTTPWebResponse. I’ve had instances where the procedures will hang indefinitely during the download. ...
6
2994
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. The code calls the bw.write(TheValue), but nothing is written after 1kb. I'm I missing something? Here's the way I create my FileStream and BinaryWriter : Filename = System.Environment.CurrentDirectory() & "\msec.dat"
3
7156
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
23556
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 returned on the ReadString call. public string BinaryRead(string fileName) { FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
4
11928
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); toClient = new BinaryWriter(networkStream); fromClient = new BinaryReader(networkStream); There is similar code on the client side. This set up works fine and communication does occur. However, the communication is very slow. This is especially...
6
4324
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, FileAccess.Read); BinaryReader br = new BinaryReader(fs); Byte bytes = br.ReadBytes(8); bytes = br.ReadBytes(1); After the first sentence, fs.Position is 0, and all things is ok, but when runs to the second sentence, i found fs.Position is 4,...
3
1797
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 like so: Public Overloads Overrides Sub Write(ByVal Value As Byte) m_Queue.Enqueue(New WriteRequest(MyBase.BaseStream.Position, Value)) End Sub 'same for all other Write variants
0
8394
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4152
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1955
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.