Tải bản đầy đủ - 0 (trang)
Part II: .NET Framework 2.0 Fundamentals

Part II: .NET Framework 2.0 Fundamentals

Tải bản đầy đủ - 0trang

Chapter7.I/OandPersistence

InThisChapter

IntroductiontoStreams

IntroductiontoBasicFileI/O

UsingAsynchronousFileI/O

WorkingwithIsolatedStorage



Inthisdayandageofenterpriseapplicationsandsmartclients

thatgettheirdatafromlargerelationaldatabaseslikeSQL

ServerandOracle,itisofteneasytooverlookthefactthatwe

stillusetheunderlyingfilesystemforsomethingotherthan

storingshortcutsanddocuments.

Weusefilesfornumeroustasks,includingstoringconfiguration

settings,images,icons,textualdata(suchascomma-delimited

filesfromothersourceslikemainframes),file-baseddatabases

suchasMicrosoftAccess,Excelspreadsheets,andevenXML

data.

Thischaptershowsyouthebasicsofworkingwithfilesusing

the.NETFramework,includinghowtoworkwithstreams,the

basicunitofinput/output(I/O)usedthroughouttheentire

framework.Finally,you'llseesomemoreadvancedfileI/O

techniquessuchasasynchronousI/Oandtheuseofisolated

storagetoprovideasecure,isolatedlocationforyour

application'sdata.







IntroductiontoStreams

Astreamisanobjectthatessentiallyconnectsdatabetween

twoendpointswithanarrowaccesswindow.Streamsallowyou

towriteandreadsmallportionsofdataatatime,providingfor

anextremelyefficientmeansofaccess.Forexample,usinga

stream,youcanreaddatainsmallportionsfromafilethatis

severalhundredmegabytesinsizewithoutactuallyconsuming

severalhundredmegabytesofmemory.Thesameistrueof

writingtostreams.Youcanplacesmallamountsofdataona

streamwithouthavingtohaveallofthedatainmemoryatany

giventime.

Inadditiontotheperformancebenefit,streamsalsoprovidea

unifiedmodelforreadingandwritingdata,regardlessofthe

formatorlocationoftheunderlyingdata.Forexample,youcan

accessdatafromadiskfileusingastreamandyoucanaccess

datafromarelationaldatabaseorfromawebserviceina

streamaswell.

Streamscanalsobeconnectedthroughaprocessreferredtoas

composition.Bycomposingstreams,youcanattachvarious

typesofreaderandwriterclassestotheendofthestreamto

makedataaccesseasier.AsyouwillseeinChapter15

"CryptographyandDataProtection,"youcanevenattach

speciallyencryptedstreamssothatdataisencryptedassoon

asitisplacedonthestream.Streamscanalsobeusedfor

networkcommunicationinadditiontofileI/O.



UsingMemoryStreams

StreamsarethebasicunitofI/Ointhe.NETFrameworkand

youwillfindthemusedeverywhere.Beforegettingintoworking

withphysicalfilesondisk,thissectionwillillustratethebasics



ofopeningstreamsandreadingandwritingfromstreamsusing

theMemoryStreamclassasanexample.Whenyouknowhowto

manipulateaMemoryStream,youwillfindthatyouwillbeableto

usealloftheothertypesofstreamsexposedby.NET

Frameworkclasseswithlittledifficulty.

Asmentionedearlier,streamsprovideanarrowwindowof

access.Thisoftencausesdeveloperstrouble.Forexample,

whenyouwritetoastream,thePositionofthepointerinthe

streamadvances.Whenyoureadfromastream,theread

alwaysstartsfromthecurrentpointerpositionwithinthe

stream.Acommonsourceofproblemswhenreadingfrom

streamsisnotsettingthepointerpositionproperlywiththeSeek

method.

BeforetakingalookattheMemoryStreamsamplecode,takealook

atTables7.1and7.2,whichlistthemethodsandproperties

thatbelongtoallStreamclasses,regardlessoftheunderlying

datastore.

Table7.1.StreamProperties

Property



Description



CanRead



Thispropertyisusedbyderivingclasses(such

asMemoryStream)toindicatewhetherthestream

supportsreadoperations.



CanWrite



Indicateswhetherthestreamsupportswrite

operations.



CanSeek



Indicateswhetherthestreamsupportsseek

operations.Somestreamsareforward-onlyand

donotallowseekingtospecificpositions.



Length



Indicatesthelength,orsize,ofthestreamin

bytes.



Position



Indicatesthecurrentpointerpositionofthe

stream.



Table7.2.StreamMethods

Method



Description



BeginRead



Startsanasynchronous(multithreaded)read

operation



BeginWrite



Startsanasynchronouswriteoperation



Close



Closesthecurrentstreamandreleases

associatedresources(suchasunderlying

databaseresources,networksockets,OS-level

filehandles,andsoon)



EndRead



Completesanasynchronousreadoperation



EndWrite



Completesanasynchronouswriteoperation



Flush



Clearsanybuffersinthestreamandstoresany

uncommitteddataintheunderlyingbacking

store



Read



Readsanarrayofbytesfromthestream



ReadByte



Readsasinglebytefromthestream



Seek



Movesthepointertotheindicatedposition,

relativetothebeginning,end,orcurrent

positionofthestream



SetLength



Expandsorcontractsthestream,ifsupported



Write



Writesanarrayofbytestothestream



WriteByte



Writesasinglebytetothestream



ThecodeshowninListing7.1illustrateshowtoinstantiatea

stream,aswellashowtoreadandwriteinformationfromthat

stream.



Listing7.1.MemoryStreamSample



usingSystem;

usingSystem.IO;

usingSystem.Collections.Generic;

usingSystem.Text;

namespaceMemStream

{

classProgram

{

staticvoidMain(string[]args)

{

stringsourceString="Maryhadalittlelamb.";

MemoryStreamms=newMemoryStream(100);

//putsomedataonthestream

ms.Write(ASCIIEncoding.ASCII.GetBytes(sourceString),

0,sourceString.Length);

Console.WriteLine("Afterinitialwrite:");

Console.WriteLine(string.Format(

"Capacity:{0}\nLength:{1}\nPosition:{2}",

ms.Capacity,ms.Length,ms.Position));

ms.Seek(0,SeekOrigin.Begin);

//readthefirst4bytesofthestream

byte[]tempBytes=newbyte[sourceString.Length];

ms.Read(tempBytes,0,4);

Console.WriteLine(ASCIIEncoding.ASCII.GetString(tempBytes));

//gettheword'lamb'

ms.Seek(-5,SeekOrigin.End);

ms.Read(tempBytes,0,4);

Console.WriteLine(ASCIIEncoding.ASCII.GetString(tempBytes));

//writesomebytes

ms.Seek(11,SeekOrigin.Begin);

ms.Write(ASCIIEncoding.ASCII.GetBytes("really"),0,6);

//nowgetthewholestream

ms.Seek(0,SeekOrigin.Begin);

ms.Read(tempBytes,0,(int)ms.Length);

Console.WriteLine(ASCIIEncoding.ASCII.GetString(tempBytes));



ms.Close();

Console.ReadLine();

}

}

}



Beforerunningthiscode,seeifyoucanpredicttheoutput.The

codethatretrievesthefirstfourbytesofthestreamshouldbe

fairlyobvious;theoutputwillbethewordMary.



WorkingwithUnicode

Whenworkingwithstreamsthatcontaintextual

data,knowingthesizeofyourcharactersis

paramount.Forexample,whenworkingwith

traditionalASCIIcharacters,thesizeofeach

characterisexactlyonebyte.Thismakesmatheasy.

However,whenworkingwithUnicodewhendealing

withforeignlanguages,youneedtorememberthat

eachcharacterrequirestwobytes.Therefore,when

youconvertbytearraysintostrings,youneedtouse

theUnicodeEncodingclass,andyouneedtoallocate

twicethenumberofcharactersinbyteswhen

initializingyourbytearrays.



Next,thecodeseekstoapositionfivebytesbeforetheendof

thestreamandthengrabsthenextfourbytes,producingthe

word"lamb."

Thenextfewlinesofcodearetypicallywherealotof

developersgetconfused.Whenyouwritetoastream,you

overwritewhateverbytesmightlieunderneath.So,when

writing"really"tothestream,youdon'tget"Maryhadareally



littlelamb."asonemightexpect.Rather,yourstreamcontains

"Maryhadareallylamb.".Ifyourgoalistrulytoinsertdataata



certainpointinthestream,andhavetheremainderofthe

streamremainintact,youwillneedtodoitthe"old-fashioned

way."Thisinvolvesusingtwostreamsandcopyingtheoldinto

thenew,makingsuretoinsertthenewdataintherightplace

inthenewstream.



IntroductiontoBasicFileI/O

Inthe.NETFramework,fileI/Oisaccomplishedusingstreams.

Althoughsomeclassesmaymakecertainaspectsofreading

andwritingtotextfileseasier,thoseclassesstillmakeuseof

streamsforthefinalreadandwriteoperationsonoperating

systemfiles.Thissectionshowsyouhowtocreate,appendto,

readfrom,andqueryinformationaboutfiles.Youwillalsosee

howtheframeworkprovidesutilityclassesforcommonfile

operations,suchastheStreamWriterclassthatisusedin

conjunctionwiththeFileclasstomakeworkingwithplaintext

fileseasy.



CreatingandAppendingFiles

WhenworkingwithfilesusingtheStreampattern,themajorityof

theworkisdoneintheconstructorfortheFileStreamclass.This

constructorallowsyoutospecifythefilename(oraclassic

Win32filehandle),aswellasaccessmodes,sharingmodes,

andmuchmore.Usingtheconstructor,youindicatewhether

youwanttocreateanewfileoropenanexistingfile,oropen

anexistingfileforappending.

Thefollowingfewlinesofcodecreateanewfileandwritesome

texttoit:

stringorigString=

"Ineversawanauthorwhowasawarethatthereisany"+

"dimensionaldifferencebetweenafactandasurmise.\n"+

"-MarkTwain";

//createthefile,writetoit,saveit.

FileStreamfs=newFileStream("quote.txt",FileMode.Create);

fs.Write(ASCIIEncoding.ASCII.GetBytes(origString),0,



origString.Length);

fs.Close();



NotethatyouneedtoclosetheFileStreaminorderforthe

contentsoftheStreamtobewrittentodisk.Asmentionedin

thedescriptionfortheStreamclass,theClosemethodreleasesall

resourcesandflushestheremainingcontentsofthebufferto

whateverunderlyingmediabacksthestream,suchasadisk

file.

Youcanuseadifferentoptionintheconstructortoobtaina

FileStreamforthesamefile,butthistimeyoucanusetheStream

toappendadditionaldatatothefile:

stringaddString=

"\n\nGoodfriends,goodbooksandasleepyconscience:"+

"thisistheideallife.\n"+

"-MarkTwain";



fs=newFileStream("quote.txt",FileMode.Append);

fs.Write(ASCIIEncoding.ASCII.GetBytes(addString),0,addString.

fs.Close();



TheprecedingcodeusestheFileMode.Appendenumerationitemto

indicatehowthefileshouldbeopened.Table7.3containsa

descriptionofeachofthepossiblefilemodes.

Table7.3.FileModeEnumerationValues

FileMode



Description



Append



Opensthefileifitexistsandseekstotheendof

thefile.Ifthefiledoesnotexist,anewfileis

created.



Create



Createsanewfile.Ifafilealreadyexistswith

theindicatedname,thefileisoverwritten.



CreateNew



Createsanewfile.Ifthefilealreadyexists,an

IOExceptionerrorwillbethrown.



Open



Opensanexistingfile.AFileNotFoundException

exceptionwillbethrownifthefiledoesnotexist.



OpenOrCreate



Opensanexistingfile.Ifthefiledoesnotexist,

itwillbecreated.



truncate



Opensanexistingfile.Afterthefileisopened,

itssizewillbereducedto0bytesandalldata

containedwithinitwillbelost.



Nowthatyouhaveseenthelow-levelwayofcreatingbasic

files,whethertheyarebinaryfilesortextfiles,let'stakealook

ataquickerandeasierwayofworkingwithtextfiles.

Youcanreplacetheprecedingcodewhereyouhavetowork

witharraysofbyteswiththefollowingcode,makingthecode

easiertoreadandsimplertowrite:

StreamWritersw=File.CreateText("quote2.txt");

sw.Write(origString);

sw.Write(addString);

sw.Close();



Asyoucansee,thecodeisalotsimplerthantheprevious

examples.Thereasonthischapterstartedoffshowingyouhow

toworkwitharraysofbytesisthatthisknowledgewillhelpyou

ifyouneedtoworkwithfilesthatdon'tcontainsimpletext,

suchasimagefilesorbinaryfilescontainingfixeddata

structures.



ReadingfromExistingFiles

ReadingfromfilesusingstreamsworksjustlikeallotherI/O

thathasbeendiscussedinthischapteruptothispoint.You

obtainareferencetothefileeitherusingtheFileStreamclass

constructororusingtheFileclass.

Whenyouhaveareferencetothefilefromwhichyouwantto

read,youcanreadthatdatausingthestream'sReadorReadByte

methods.

ThefollowingcodeusesaFileStreamclasstoopenanexisting

file,readanarrayofbytesfromit,anddisplaytheresulting

arrayofbytesasanASCIIstring:



byte[]fileBytes=newbyte[origString.Length+addString.Lengt

fs=newFileStream("quote.txt",FileMode.Open);

fs.Read(fileBytes,0,(int)fs.Length);

Console.WriteLine("Quotefromthefile:");

Console.WriteLine(ASCIIEncoding.ASCII.GetString(fileBytes));



AndnowtakealookatthesameeffectusingtheOpenText

methodoftheFileclasstocreateaninstanceoftheStreamReader

class:

StreamReadersr=File.OpenText("quote2.txt");

Console.WriteLine("Entirefile:\n"+sr.ReadToEnd());

sr.Close();



UsingDirectoriesandtheFileSystem



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Part II: .NET Framework 2.0 Fundamentals

Tải bản đầy đủ ngay(0 tr)

×