Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

Classes to read/write data to a series of bytes [CODE]

This is come code I've written and I use to read and write stuff to a byte array. This is very useful for transmitting data over sockets.
http://pastie.org/private/991hwnpj2gfmdi4bs6hxa
Enjoy! This is distrubuted under a simple license: Use it freely, include credits when distrubuted as source, free to modify as long as some credits are given.
(By credits, I mean a simple code comment)
ヽ༼ຈل͜ຈ༽ノ
why: DataWriter : IDisposable
if you dont dispose anything in the class ? :D

you could at least write:
PHP Code

<?php 
/// <summary>
  /// Dispose of this object, freeing up all used memory.
  /// </summary>
  
public void Dispose()
  {
     if(array==
null)return;
     array.
clear();
     array=
null;
  } 

yo could do:

PHP Code

<?php 
/// <summary>
  /// Adds the data onto the byte array, in T form.
  /// </summary>
  /// <param name="data">The data to add onto the array.</param>
  
public void Write<T>(T data)
  {
    if(
typeof(T)==typeof(string))
    array.
AddRange(ASCIIEncoding.Default.GetBytes(data));
    else
    array.
AddRange(BitConverter.GetBytes(data));
  } 


For your read i would rather use it more generic

PHP Code

<?php 
//pseudo code
 
public byte[] Read<T>()
{
List<
T> bytes = new List<T>();

for(var 
i = 0; i<sizeof(T);i++)
{
bytes.Add(_stream.ReadByte());
}
    return 
bytes.ToArray();
  } 

the reason is, you could send and read custom types and convert them, with your method you are stuck to what you provide and you have to extend the class all the time...


just suggestions - if i am wrong or you have different reasons feel free to express them and explain it to me :)



P.S. to send custom types/classes you need to restructure the code a bit more and use
BinaryFormatter / serialization blabla blupp .. google is our friend :)
PHP Code

<?php 
public override string ToString()
  {
    return 
ASCIIEncoding.Default.GetString(ToBytes());
  } 

Use UTF8, not ASCII.

EDIT:
PHP Code

<?php 
~DataReader()
  {
    
Dispose();
  } 

Not needed, CLR calls Dispose automatically on destruction.

P.S. Use destructors only as fallback mechanism, because you can't control when GC will do the cleanup for this object (if it ever does.)


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Python] by Luffy-_-Jan 11, 2022 08:14 AM 5 162 Jan 11, 2022 08:14 AM
Last Post: Hackers
[C] by zNinjaApr 5, 2020 01:24 PM 3 144 Apr 5, 2020 01:24 PM
Last Post: Mysticism
[.NET] by fisica638Nov 4, 2019 10:07 AM 8 384 Nov 4, 2019 10:07 AM
Last Post: fisica638