Chapter109:Stream

No Comments

Section109.1:UsingStreams

Astreamisanobjectthatprovidesalow-levelmeanstotransferdata.Theythemselvesdonotactasdata containers.

Thedatathatwedealwithisinformofbytearray(byte[]).Thefunctionsforreadingandwritingareallbyte orientated, e.g. WriteByte().

Therearenofunctionsfordealingwithintegers,stringsetc.Thismakesthestreamverygeneral-purpose,butless simpletoworkwithif,say,youjustwanttotransfertext.Streamscanbeparticularlyveryhelpfulwhenyouare dealing with large amount of data.

WewillneedtousedifferenttypeofStreambasedwhereitneedstobewritten/readfrom(i.e.thebackingstore). Forexample,ifthesourceisafile,weneedtouseFileStream:

stringfilePath=@”c:\Users\exampleuser\Documents\userinputlog.txt”;

using(FileStreamfs=newFileStream(filePath,FileMode.Open,FileAccess.Read, FileShare.ReadWrite))

{

//dostuffhere…

fs.Close();

}

Similarly,MemoryStreamisusedifthebackingstoreismemory:

//Readallbytesinfromafileonthedisk.

byte[]file=File.ReadAllBytes(“C:\\file.txt”);

//Createamemorystreamfromthosebytes.

using(MemoryStreammemory=newMemoryStream(file))

{

//dostuffhere…

}

Similarly,System.Net.Sockets.NetworkStreamisusedfornetworkaccess.

AllStreamsarederivedfromthegenericclassSystem.IO.Stream.Datacannotbedirectlyreadorwrittenfrom streams.The.NETFrameworkprovideshelperclassessuchasStreamReader,StreamWriter,BinaryReaderand BinaryWriterthatconvertbetweennativetypesandthelow-levelstreaminterface,andtransferthedatatoor from the stream for you.

ReadingandwritingtostreamscanbedoneviaStreamReaderandStreamWriter.Oneshouldbecarefulwhen closingthese.Bydefault,closingwillalsoclosecontainedstreamaswellandmakeitunusableforfurtheruses.This defaultbehaviourcanbechangebyusingaconstructorwhichhasboolleaveOpenparameterandsettingitsvalue as true.

StreamWriter:

FileStreamfs=newFileStream(“sample.txt”,FileMode.Create);

StreamWritersw=newStreamWriter(fs);

stringNextLine=”Thisistheappendedline.”; sw.Write(NextLine);

sw.Close();

//fs.Close();Thereisnoneedtoclosefs.Closingswwillalsoclosethestreamitcontains.

StreamReader:

using(varms=newMemoryStream())

{

StreamWritersw=newStreamWriter(ms); sw.Write(123);

//sw.Close();                Thiswillclosemsandwhenwetrytousemslateritwillcauseanexception

sw.Flush();               //Youcansendtheremainingdatatostream.Closingwilldothisautomatically

//Weneedtosetthepositionto0inordertoread

//fromthebeginning.

ms.Position=0;

StreamReadersr=newStreamReader(ms);

varmyStr=sr.ReadToEnd();sr.Close();

ms.Close();

}

SinceClassesStream,StreamReader,StreamWriter,etc.implementtheIDisposableinterface,wecancallthe

Dispose()methodon objectsof theseclasses.

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment