Tải bản đầy đủ - 0 (trang)
Chapter 12. File I/O and Serialization

Chapter 12. File I/O and Serialization

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

Section12.16.RecreatingObjectswithDeserialization

Section12.17.PreventingObjectItemsfromBeing

Serialized

Section12.18.CustomizingtheSerializationProcess



12.0Introduction

Thischaptershowsthenecessarystepstoreadandwritetoa

file,usethelocalfilesystem,andcreatepersistentobjects

throughaprocessknownasserialization.Thischapterreally

servesasthefoundationforsomeofthedataaccesschapters

intheremainderofthissection.Forinstance,inthenext

chapter,you'llseehowtoreadandwriteXMLfiles.The

methodsfordoingsotieintotheinformationinthischapter.



12.1CreatingaNewFile

Youwanttoprogrammaticallycreateanewfileonthelocalfilesystem.



Technique

Oneofthefirstthingsyouhavetoconsiderbeforeyoustart

writingthecodetowritedatatoafileisthefileformat.When

wesayfileformat,however,wedon'tmeanhowthedataitself

islogicallyorganizedwithinthefilebutinsteadthetypeofdata

thatwilleventuallybewritten.Afileiseithertext-basedor

binary,althoughthedifferencesbetweenthetwoarefuzzy

becausefilesbynaturearealwaysbinary.However,text-based

fileformatswritedataoutaccordingtoitsstringrepresentation.

Forinstance,ifyouwanttowriteintegervaluestoatextfile,

theASCIIvaluesoftheintegersratherthantheintegers

themselvesarewritten.Inotherwords,ifyouwritetheinteger

42toatextfile,youactuallywritetheASCIIequivalentof0x34

and0x32,representingeachdigit.Abinaryformattingscheme

usestheactualvalueof42.

Tocreatenewfileinpreparationforwritingtext,usethe

StreamWriterclassinconjunctionwiththeFile.CreateText

method.TheCreateTextmethodhasasingleparameter,which

isthepathofthefiletocreate:



privatevoidSaveText(stringtext,stringfile)

{

StreamWritersw=null;



try

{

//1.Creatinganewfilefortextoutput

sw=File.CreateText(file);

}

catch(Exceptione)

{

MessageBox.Show(e.Message);

}

finally

{

if(sw!=null)

sw.Close();

}



}

Wheneverdataiswrittenusingthemethodjustmentioned,

dataisconvertedtoitsASCIIequivalent.Wheneveryouopen

thefileinasimpletexteditor,thedataisreadable.The

converseiswritingbinarydata.Thereareamyriaddifferent

waystocreateafileforbinaryoutput.Oneofthese,similarto

themethodshownearlier,istocalltheCreatemethoddefined

intheFileclass.ThismethodreturnsaFileStreamobject:



privatevoidSaveBinary(byte[]bytes,stringfile)

{

FileStreamfs=null;



try

{

if(File.Exists(file))

{

File.Delete(file);

}



//1.Creatinganewfileforbinaryoutput

fs=File.Create(file);

fs.Write(bytes,0,bytes.Length);

}

catch(Exceptione)

{

MessageBox.Show(e.Message);

}

finally

{

if(fs!=null)

fs.Close();

}

}



Comments

Theconceptoftext-andbinary-basedfileformatsisan

importantone.Eachonehasitsadvantagesanddisadvantages.

Insomecases,however,theansweronwhichformattosupport



isprettyclearcut.Text-basedformatshavethedistinct

advantageofhumanreadability.Ifyourapplicationusesatextbasedfileformats,youhavealargeassortmentofexternal

text-editingtoolsatyourdisposal.Sure,youcaneditbinary

filesusingahexeditor,butthepossibilityofenteringbaddata

isextremelyhighinthosecircumstances.Onedisadvantageof

textthatisanadvantageforbinaryfilesissize.Ifyourecall,

theinteger42actuallytranslatesinto2bytesinatextfile,one

foreachdigit.Inabinaryfile,youcanwritethatsamedatain

only1byte.Whenthedataisofconsiderablesize,theresultant

filesizeisordersofmagnitudebiggerinatext-basedformat

thaninabinaryformat.

TheStreamWriterandFileStreamclassesareboth

specializationsofcertain.NETbaseclasses.TheStreamWriter

isaTextWriterobject,whichmakessensebecauseitspurpose

istowritetextualdatatoafile.Someoftheotherderived

classesincludetheHtmlTextWriter,whichcontainsmethodsto

outputHTMLtagsandattributes;theStringWriter,which

performswritingonastringobjectratherthananactualfile;

andtheHttpWriterclass,whichsendsdatatoaremoteclient

application.

TheFileStreamisoneclassinagroupofStream-based

classes.Someoftheseclassesaredesignedtoworkwithbinary

valuesinmemory,networking,andcryptography.Eachoneof

theseclassessimplyrepresentsaspecializedwaytowriteouta

sequenceofbytestotheirapplicabledestinations.



12.2VerifyingtheExistenceofaFile

Youwanttoverifythatafileexistsgiventhepathtothatfile.



Technique

TheFileclasscontainsamethodnamedExists,whichreturns

aBooleanvalue:



if(File.Exists(file))

{

File.Delete(file);

}



Comments

TheExistsmethodreturnstrueifafileexistsataspecified

locationorfalseifitdoesn't.However,ifthecurrentsecurity

permissionsonthefiledon'tallowtheusertoaccessit,the

Existsmethodreturnsfalseeventhoughthefiledoesexist.



Thepathtothefilecanbeeitherarelativeorabsolutepath.An

absolutepathisthefullpathofthefilestartingfromthedrive

letter.Afilenamedfile.txtlocatedinthetempdirectoryof

theharddrivethereforehasanabsolutepathof



c:\temp\file.txt

Arelativepathmeansthefileisrelativetoacertainlocation.

Thislocationisthecurrentdirectoryoftheoperatingsystem.

Takenotethatitisn'talwaysthedirectoryyourapplicationis

runningin.Todeterminethecurrentdirectory,callthestatic

methodDirectory.GetCurrentDirectory.Ifyoudoinfact

wanttoretrievethedirectorythatyourapplicationisrunning

from,callthestaticmethodApplication.StartupPath.An

exampleofanapptryingtodiscovertheexistenceofitself

includescodesuchasthefollowing:



Directory.SetCurrentDirectory(Application.StartupPath);

if(File.Exists("1_FileView.exe"))

{

MessageBox.Show("IAm");

}



12.3OpeningaFileforReadingUsingtheFile

Class

Youwanttoopenafileforreadingeithertextorbinarydata.



Technique

Thetechniqueforopeningafileissimilartothetechniquesin

Section12.1,"CreatingaNewFile."However,insteadoftwo

methodsbasedoneithertextorbinaryformats,openingafile

actuallyhasthree.Thecommentssectionexplainswhyathird

methodexists.

Toopenafilefortext-basedreading,calltheOpenTextmethod

definedintheFileclass.LikeallmethodsintheFileclass,it

isstatic,soyoudon'tneedaFileobjectinstance.OpenText

returnsaStreamReaderobjectusedtoeventuallyreadthe

textualdatafromthefile:



privatestringOpenText(stringfile)

{

StreamReadersr=null;



try

{

//openthefile

sr=File.OpenText(file);

}

catch(Exceptione)

{

MessageBox.Show(e.Message);

}

finally

{

//closetheStreamReader

if(sr!=null)

sr.Close();

}



//placeholder

return"";



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

Chapter 12. File I/O and Serialization

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

×