I had to write this quick little adapter the other day for something and figured it might be useful for people …
In general you are better off making the code that is using a stream not use a stream but to use an IEnumerable<byte []> since using stream you are required to copy … Buy for very large buffers this is far more efficient than copying into a MemoryStream.
10 public class IteratorStream : Stream
11 {
12 private readonly IEnumerator<byte[]> m_Chunks;
13 private ArraySegment<byte> m_CurrentChunk;
14
15 public IteratorStream(IEnumerable<byte[]> _Chunks)
16 {
17 if (_Chunks == null) throw new ArgumentNullException();
18 m_Chunks = _Chunks.GetEnumerator();
19 }
20
21 public override bool CanRead {
22 get { return true; }
23 }
24
25 public override bool CanSeek
26 {
27 get { return false; }
28 }
29
30 public override bool CanWrite {
31 get { return false; }
32 }
33 public override long Length { get { return -1; } }
34
35 public override long Position
36 {
37 get { throw new NotImplementedException(); }
38 set{ throw new NotImplementedException();}
39 }
40
41 private bool ReadNextChunk()
42 {
43 bool HasMore = m_Chunks.MoveNext();
44 if (HasMore)
45 {
46 m_CurrentChunk = new ArraySegment<byte>(m_Chunks.Current);
47 }
48 return HasMore;
49 }
50
51 public override int Read(byte[] buffer, int offset, int count) {
52 if (buffer == null) throw new ArgumentNullException(“buffer”);
53 if (offset < 0 || offset >= buffer.Length) throw new ArgumentException(“offset must be greater than or equal to 0 and less than the size of the buffer”);
54 if (count < 0) throw new ArgumentException(“count must be greater than or equal to 0″);
55 if (offset + count > buffer.Length) throw new ArgumentException(“offset + count must be less than the buffer size”);
56
57 int LeftToRead = count;
58 int CurrentLocation = offset;
59 if (m_CurrentChunk.Count == 0)
60 {
61 if (!ReadNextChunk())
62 {
63 return 0;
64 }
65 }
66 while (LeftToRead > 0 && m_CurrentChunk.Count != 0)
67 {
68 int toRead = (LeftToRead > m_CurrentChunk.Count) ? m_CurrentChunk.Count : LeftToRead;
69 Buffer.BlockCopy(m_CurrentChunk.Array, m_CurrentChunk.Offset, buffer, CurrentLocation, toRead);
70 LeftToRead -= toRead;
71 CurrentLocation += toRead;
72 m_CurrentChunk = new ArraySegment<byte>(m_CurrentChunk.Array, m_CurrentChunk.Offset + toRead, m_CurrentChunk.Count – toRead);
73 if (m_CurrentChunk.Count == 0)
74 {
75 ReadNextChunk();
76 }
77 }
78 return count – LeftToRead;
79 }
80
81 protected override void Dispose(bool disposing)
82 {
83 base.Dispose(disposing);
84 if (disposing && m_Chunks != null)
85 {
86 m_Chunks.Dispose();
87 }
88
89 }
90
91 public override long Seek(long offset, SeekOrigin loc) { throw new NotImplementedException(); }
92 public override void SetLength(long value) { throw new NotImplementedException(); }
93 public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); }
94 public override void Flush() { throw new NotImplementedException(); }
95 public override void WriteByte(byte value) { throw new NotImplementedException(); }
96 }
97
98
99 class Program
100 {
101 static IEnumerable<byte[]> GetBytes()
102 {
103 byte [] OneToTen = new byte[10];
104 for(byte i=0;i<10;i++)
105 OneToTen[i] = i;
106 for(int j = 0;j <10;j++) {
107 yield return OneToTen;
108 }
109 }
110
111 static void Main(string[] args)
112 {
113 IteratorStream stream;
114 using (stream = new IteratorStream(GetBytes()))
115 {
116 int read = stream.ReadByte();
117
118 //read 1 byte at a time
119 while (read != -1)
120 {
121 Console.WriteLine(read.ToString());
122 read = stream.ReadByte();
123 }
124 }
125
126 //read 100 bytes
127 using (stream = new IteratorStream(GetBytes()))
128 {
129 byte[] buffer = new byte[100];
130 int read = stream.Read(buffer, 0, 100);
131 Console.WriteLine(read);
132 }
133
134 }
135 }
55IR3g
gaia online theme layouts
bank lafayette trust
bank online pnc
how to refinance home
south walton beaches
beauty the beast soundtrack
a death mask
download free mobile ringtone
jack daniels whiskey
i could lyrics
direct download anime
the pansy flower
mental health new
credit counselors in
clothing dallas vintage
bob marley wailers
what is traditional
choppers custom kits
letoya luckett video torn
early symptom of pregnancy
south park video
pokemon red walkthroughs
blank resume form
low fat dessert
black and decker coffee makers
management risk software
lose 10 pound in 3 day
live images of a satellite
wish you were here and incubus
politics and religions
last testament and will
you go for it
maps for paris france
video software download
bush in the polls
types of governments
girls bras pics
houses for rent in san diego
suggest you to do
air credit cards
music billboard top 100
www gander mountain
death of bruce lee
whats my sign
frankie j and baby bash
list of missing
tv channel guides
rent homes in san diego
www cbse nic in
laa an der thaya
mujeres haciendo el amor
status of tax refund check
livingston news parish
list of all breeds dogs
do you want to know
greek food recipies
hp 3820 deskjet driver
torrent site downloads
what is overdrive for
charter of rights and freedoms
the story of my life
macromedia 2004 mx
adware spyware removers
look at my boob
code coupon secret victorias
advance cash payroll
dsc s60 sony
brandon jackson t
vacation mexico cheap
dick free pics
benjamin moore paints
software for pocket pc free
raise your hand
accessories for bmw
the five kingdoms
air force ones nike release dates
asian man on white
hot gallery girl
send out to
all about rainforest animals
sisters hot friend
seven day battles
cable box descrambler
cheat codes for the godfather ps2
ohio state universtiy
jewlery television com
best dvd softwares
ovulation to pregnancy
rent a apt
free people searches
animated desktops free
junk yard houston
shock wave daily jigsaw
canterbury tales the prioress tale
movie trailers sex
butternut squash soup with
leaders of all time
how to do the chicken dance
free teen titans hentai
eagan estate mn real
what is psychoanalytic
mark twain the biography
japanese translate english
new york snow
a dollhouse ibsen
lemon chicken recipies
hot lesbian girls
recipes for chicken wings
a dream is wish lyrics
from couch potato
measure of man
lyrics for gavin degraw
farm insurance life state
bach christian johann
mercado livre brazil
lexus of jackson mississippi
kwon tae usa
what is cashflow management
what is irrational number
pontiac fort myers
advise me on
plump the rump
delta force black hawk down
a wear fashion
on the verge of
make a happy
horror rocky show
small bussiness software
free online rpg multiplayer games
chicken roast recipe
breaking news and
lottery winners stories
how to remote desktop connection
let love in goo dolls lyrics
lyrics for pieces by sum 41
saturday night live ticket
baby bash frankie
what is discursive
reform in education
revenge pics girlfriends
scrap aluminum prices
free online college courses
your my little secret lyrics
coffee maker best
grayhound bus station
deluxe download free print shop
first time video girls
resort on cocoa beach
kristen story archieves
st thomas hospital
the tabula rasa
eggs and chicken
online games kids free
florida home loan naples
california driving fremont school
gangstas lyric paradise
the hogan stand
bullmastiff for sale
fulton county goverment
holiday gift ideas
chalet a louer
breaking benjamin so cold lyric
to be killed
work from home on computer
stage clothing stores
buy direct in canada
america west arilines
pet monkey for sale
surface mount amplifier
picture of bathroom
rentals long beach
the epstein barr virus
how to repair lcd monitor
los angeles airport hotels
click five girl just
lists of names for babies
the roman emperors
xxx web cams
scotland travel package
batman and robin in
cook dane myspace com site
persecution of christian
imports car show
ralph lauren home
dont date her
distance on map
lazer whitening teeth
jen n dave
employment security commission south carolina
hospital for special
treatment of hemorrhoids
usb driver windows98
trabuco hills highschool
effects of creatine
spy camel toes
county erie new york
dance and fall out boy
jabatan perdana menteri
bar build home
boy or girl pregnancy
become a pornstar
child dangerously destiny in love
air express india
i beam wood
hot tub rentals
credit cards with cashback
the vice president of us
for mac computers
vacation packages orlando
what is islam about
where can i find poems at
book reviews children
a destination wedding
symantec antivirus virus
lyrics for circa survive
john lennon how lyrics
lyrics to edwin mccain i
what is a cavity
greek restaurant washington
how to togas
theme xp downloads
home sale vallejo
the elders scroll 3
testimonies of christians
city chicago colleges
lexus is 350
holocaust oskar schindler
the life of david gale
dentists park rapids
baltimore apartments rent
greek islands maps
waht time is it
day dustins life our page
poker chips to buy
what to wear at work
video of laffy taffy
latest nokia mobile phone
lyrics to nat king cole
what men are looking for
home study traffic school
natural cures they
magic of the gathering
bear feet shoe
bay area map
downtown houston map
if hope die
county fairgrounds orange
backup window xp
symptoms of brain tumors
ocean isle beach nc
www honda motorcycle
loan consolidation for private loans
cheats for sims 2 on playstation
the palace resort
area agencies on
video poker games free
dealer farm vehicle
health insurance oregon
cristy site myspace com
girls party dresses
dakota state univ
archive search sltrib com vertical
new york boot camp
download indian songs for free
pattcu com wright
the journal nature
debra messing oops
know you are in love
bad girl myspace com site
calorie negative foods
computerized time clocks
medical billing services
for netgear router
clip gay sex
how to rap dance
spring arbor university
paris hilton photos
airline schedule united
the eye anatomy
inns of court
malay songs lyrics
item warcraft world
dog names males
dont be a menace
chicago injury lawyers
loved ones poems
bird photo wild
first love utada hikaru
toronto canada map
mail php pinch webnomey net
in sleep smile
cards birthday funny
wal mart download music
a good name
philadelphia junk yard
www real couples
hostname welcome hp ww com
tapestry wall hanging
author of a book
how to buy a notebook computer
by the wire
neck pain and
indian film wallpapers
boys in speedos gallery
ecommerce web site builder
emo myspace com ranger site
college basketball schedules
full house pictuers
thinking about of you
baltimore county library
the daily freeman
basic chords for guitars
join the club
times india news
templates on microsoft
resorts hotel atlantic city new jersey
map of black sea
skin care products for aging
demos of games
cell phone with gsm
slim fast diet plans
calculator for mortgages
teen dateing advice
free bisexual video
violnce against women
bass free tab
easy pasta recipies
court fresno superior
two thrones cheats
license pilot private
men s bracelets
starbucks food nutrition fact
agent become estate real
about the burrowing owl
uk recruitment agencies
you are blanche
what is time management skills
wheel of fortune online games
woodworking wood supply
viper bar hauppauge ny
schmick and mccormick
invest in for
recipe for shrimp alfredo
what is economic growth
box cnbc squawk
body shots movie
quilt with pictures
scarface world is yours
americas top model
free dateing sites
cribbage playing rule
disneys high school musical
nip slips lohan
angeles hair in laser los removal
a medical dictionary
district joliet park
county defensive driving orange
hotel green bay wi
recipe for turkey meatloaf
a dearth of
univ of michigan football
bar salad soup
jobs in washingtondc
new york locksmith
used trucks dealers
jobs vacancy in dubai
portland international airport
gay las vegas
ibm ac adapter
zelda sheet music
the banana republic store
gas las station vegas
dxg digital camera
what is midlife crisis
fort health insurance worth
thrifty car coupons
mama para tarjetas
the labrador retriever
hot thai girls
you got what i like
the bank of glen burnie
ford used cars
making a volcanoe
killer whale pictures
coloring free picture
background web site
cum on lips
ps2 mod chip
berkner high school
nissan dealers pittsburgh
www msnbc com
what is in your heart pendant
ccars for sale
sex cam chat
chair and a half
medical supplies for home
gameboy color roms
convert 3 inch
zanies comedy clubs
what is a black box
department florida labor
fl lotto official
the sea gull
homeowner s insurance rates
experiential learning styles
a historical document
estate gatlinburg real tn
at a reduction
shooping in london
necklace of gold
love and hearts
halle berry nude
ice mold sculpture
lease over take
seats for bikes
concerts in atlanta
how to give thanks
educational journal leadership
a kiss from rose lyric
i am for real
grams to pounds conversion
bang dong gi shin
university of tennesee memphis
ford center for the performing
cramps in muscle
free thong pics
art institute online
decision making tools
lyell federal credit union
information on global warming
jazz festival montreal
what is barometric pressure
death di photo princess
sample of fax cover sheet
interior designs pictures
island palms resort
babel fish altavista translations
question for couples
park national bank
mp3 songs for free download
california mexican restaurants
by marriott suite towneplace
wedding scroll invitations
channels of distribution
pictures optical illusions
action figure lord ring
how to cut mens hair styles
brad pitt baby
boy fall pete wentz
lord and taylor store
book date harry potter release
what is standard deviation formula
how to dredge
north america map
kenny chesney site myspace com
first time boys
lyrics to get busy sean paul
atlanta civic center
management of it
little rock ar hotel
wetting your pants
millionaire online games
services on the internet
mah jong online
how to find jobs online
star trek nude
how to jack off
black out party
night club cleveland ohio
charlotte nc airport
poison ivy photo
south of nowhere
summary of movie
boat sail sale used
dark faeries pictures
phone number findings
pictures of violets
invitaitons invitation wedding
alice in wonderland caterpiller
hairstyles pictures short
kids party ideas
car lease calculators
free public proxy servers
brake service st louis
be so strong
services site trash
bang gang myspace com site
a map of united states america
jessica alba nude pic
symptoms of thyroid problem
pittsburgh toyota dealer
what is sarin
polka dot myspace layouts
directions on a map
cry i tonight wanna
what is ip phone system
and silver rings
journal meriden record
what to do with iso
new york cheesecake recipes
put videos on myspace
hentai love hina
print your own invitations
church suits for women
windoes media encoder
minnesota twin cities
comedies on dvd
author larry carver type gallery
lyrics to waterfalls tlc
accelerators for dial up
joann crafts fabric
heating degree days
insurance collector car
books for book clubs
silk flowers wedding
making money with internet
fix your ps2
businesss for sale
i am unemployed
the bulge in my pants
girls of lowrider
hollaback girl gwen stefani
symtoms of h pylori
dropout high school
non for profit jobs
americans for african
the fucking champs
jack nicholson movies
civil rights lawyers
resturants in nyc
illustrated lovemaking positions
dvi hdmi cable
strip poker picture
travel to costa rica
a resume for job
choclate mousse recipes
group miami related
games to download for pc
flower girls gifts
the phenomenal woman
the han dynasty
poverty in the states
theme from rocky
my checking account
free adult site
arthritis dog in
manchester new hampshire airport
are lactose intolerant
counter strike sprays
soup with cabbage
furniture by broyhill
white telephone pages
what is opac
dog system tracking
crochet poncho patterns free
sacramento news review
oceanside real estate california
international paper company
what is spousal
for interest in
missouri criminal records search
what is multiple personalities
recipe for chocolate chip cookies
terrell nemons and cedar hill
my latin wife
fast times at the nau
dvd recorders vhs
bmw fort collins
how to do sign language
free tabs for guitars
google image satellite
hear tell them they want
yom kippur wars
tia and tamera
ronaldinho soccer clip
long movie clips free
www budget car hire
gin blossom lyrics
closer movie soundtracks
cheats for baldurs gate
froogle google com hostname
chip gregory heritage
what tarot card are you
city enter name
a blaze of glory
star of bethlehem
for sell by owner houses
human resources recruiting
pictures from the movie grease
inch meter conversion
dil pagal hai
my college teacher
sugar glider picture
black eyed peas photo
porn search engines
lyrics to the rap
parking ticket in
rex appliance and tv
babes the goose
fast cash personal loans
valley of kings egypt
what to watch out for
jana and defi
secured credit cards
florida jacksonville mini
wet and wild girl
www barbie com
free download for the sims 1
honduras la ceiba
what is world poverty
my opera com
how do you what
paint and colors
customer service telephone
city of hope
screen printed shirts
fairy tattoos designs
bare feet maniac
the personal computer
it singapore training
the fear factory
what used car
burner dvd free software
what to do in new jersey
stainless steel flatware
auto insurance nationwide
printers for digital photos
live video sex
gay having sex
cast and crew
tonight is all about
what is ribosomes
knitting patterns free easy
thats all lyrics
verizon wireless login
san antonio radio station
morton pumpkin festival
oil mixed wrestling
be present for
dc myspace com site talk
student bad credit loans
play naruto mugen online characters
disneychannel com high musical school
sportys pilot shops
shrink wrap machine
cat owl pussy
progesterone natural cream
Very nice site!
Very nice site! cheap cialis http://oieypxa.com/oryrqqr/4.html
Very nice site! [url=http://oieypxa.com/oryrqqr/2.html]cheap cialis[/url]
Very nice site! cheap viagra
To the person asking for email … you can reach me at grzegoryzyozung1 at gmail
remove the z’s
friend: http://codekeep.net/snippets/eaf9ff76-df10-4b86-9805-65ba95568cdb.aspx
plz post your code snippets at http://www.codekeep.net
Here is the URL to the code … just put into a quick console application
http://codebetter.com/files/folders/codebetter_downloads/entry175969.aspx
This is cool but the code is a mess because of the host being smart about smiley’s and such. Do you think you could provide it as a downloadable .cs?