Input/Output with
m NET Framework Class Library
Pham Minh Tuan
Trang 2
a a dung trinh bay
Trang 3a the File System m Nhu cầu: „ Làm sao biết được trên hệ thống có những ổ đĩa nào?
„ Làm sao lấy được danh sách tập tin và thư mục con của một thư mục nào đó?
„ Làm sao truy xuất được các thuộc tính của mội tập tin, thư mục?
„ Làm sao giám sát được sự thay đổi của một tập
Trang 5a Navigating the File System | Drivelnfo class Thuộc tính Name Description AvailablePreeSpace |Gets the amount of available space on the drive The amount might DriveFormat Drive Type isReady Name RootDirectory TotalPreeSpace Totaisize VobhbumeLabel
be different from the amount returned by TotalFreeSpace (described later in this table), depending on disk quotas
Gets the format of the drive, such as NIFS or FAT32
Gets the type of drive in the form of the DriveType enumeration (which is described in the following section)
Gets the status of the drive, indicating whether it is ready to be accessed
Gets the name of the drive
Gets a Directoryinfo object that represents the root directory of the
drive |
Gets the total amount of free space on the drive Gets the total size of the drive
Trang 6Navigating the File System
Drivel nfo class
DriveType enum
Name Description
CDRom An optical drive It can be CD-ROM, DVD, and so on
Fixed A fixed disk
Network A network mapped drive
NoRootDirectory |A drive that does not have a root directory
Ram ARAM drive
Removable A drive that has removable media
Unknown The drive could not be determined
Phương thức Name Description
Trang 7a Navigating the File System | FileSystemI|nfo class Thuộc tính Name Description
Attributes Gets or sets FileAttributes of the current file or directory
CreationTime |Gets or sets the time that the current file or directory was created Exists Determines whether the file or directory exists
Extension Gets a string representation of the extension part of the file or directory PullName Gets the full path to the file or directory
LastAccessTime |Gets or sets the time the file or directory was accessed LastWriteTime |Gets or sets the time the file or directory was last written to
Trang 8a Navigating the File System
FileSystemI|nfo class Phương thức
Name (|Description
Delete \Removes the file or directory from the file system
Refresh \Updates the data in the class with the most current information from the file
Trang 9a Navigating the File System
Directoryl nfo class Thuộc tính
Name Description
Parent \Gets the Directoryinfo object for the parent directory of the
current directory in the directory hierarchy
Trang 10ae the File System =» Directorylnfo class Phương thức Name Description Create Creates the directory described in the current Lirectorylnfo object
CreateSubdirectory |Creates a new directory as a child directory of the current directory in the directory hierarchy
GetDirectories Retrieves an array of Directoryinfo objects that represent subdirectories of the current directory Get Files Retrieves an array of File/nyfo objects that represent
all the files in the current directory
GethileSysteminjfos |Retrieves an array of FileSystemlnfo objects that represent both files and subdirectories in the current directory
Trang 11Navigating the File System
Filelnfo class
Thuộc tính
Name Description
Lirectory Gets the Directory/nfo object that represents the directory
that this file 1s stored within
Trang 12a Navigating the File System | Filelnfo class Phương thức Name Description Append Text |Creates a new Stream Writer that will allow appending text to the file CapyTo Create CreateText Decrypt Open Write Replace
Makes a copy of the file in a new location
Creates a file based on the current file information
Creates a new Stream Writer and a new file for writing text Decrypts a file that was encrypted by the current user
Encrypts a file so that only the current user can decrypt the information within the file
Moves the file to a new location
Opens the file with specific privileges (read, read/write, and so on) Opens the file with read-only access
Opens the file and returns a Stream Reader to allow reading of text within the file
Opens the file with write-only access
Trang 13ae the File System =» Path class Phương thức Combine GetlDirectoryName Crethxtension GethileName Cret hile Name WithoutEkxtension GethullPath Description
Takes a path and returns a new path with the file name's extension changed (Note that only the path string
changes, not the actual file name extension.) Combines two compatible path strings
Returns the name of the directory in the specified path Returns the name of the file extension in the specified path
Returns the name of the file in the specified path
Returns the file name without the extension in the
specified path
Trang 14ae the File System =» Path class Phương thức CretPathRoot CetRandomPileName GetTempPileName GetTempPath HasHxtension isPathRooted
Returns the root directory name in the specified path
Generates arandom file name
Generates a temporary file in the file system and returns the full path to the file
Returns the path to the temporary file directory for the
current user or system
Indicates whether a specified path's file name has an extension
Trang 15a Navigating the File System | FileSystemWatcher class Thuộc tính Name NmuabieaisingVvemnfs Filter lucludeSubdirectories NotifvPilter Description
Gets or sets whether the watcher object should raise events Normally, it's used to turn on and off the watching ofa directory and/or files
Gets or sets the file filter to use to determine which file changes to monitor A blank filter indicates "all files."
Gets or sets an indicator of whether the watching ofa directory 1s to include subdirectories or only the directory specified in the Path
property
Gets or sets the type of changes to watch for By default, all
changes (creation, deletion, renamed files, and modifications) are notified
Trang 16Navigating the File System
FileSystemWatcher class Phương thức
Name Description
WaithorChanged |Synchronous method for watching a directory for changes and for returning a structure that contains all the changes
Su kiện
Name (|Description
Trang 17
a the File System » Lam sao biết được trên hệ thống có những ổ đĩa
nào?
Drivelnfo[] drives = Drivelnfo.GetDrives(); foreach (Drivelnfo drive in drives)
Console.WriteLine("Drive: {0}", drive.Name); Console.WriteLine("Type: {0}",
Trang 18
a the File System
„ Làm sao lẫy được danh sách tập tin và thư mục con của một thư mục nào đó?
Trang 19
a the File System
Trang 20
a the File System
= Lam sao giam sat được sự thay đổi của một tập tin, thư mục?
Trang 21
a the File System
Cung cấp tất cả các phương thức cần thiết
cho việc tạo file, xóa file, di chuyển file, sao chep file
Cung cấp tất cả các phương thức cần thiết
cho việc tạo thư mục, xóa thư mục, dị
Trang 22
ac: and Writing Files
=» Stream class
=» FileStream class
» StreamReader class, StreamWriter class
» BinaryReader class, BinaryWriter class » Memorystream class
Trang 23§) Reading and Writing Files | Siream class Thuộc tính Name Description
Can Read Determines whether the stream supports reading CanSeek Determines whether the stream supports seeking CanTimeout Determines whether the stream can time out CanWrite Determines whether the stream can be written to Length Gets the length (in bytes) of the stream
Position Gets or sets the virtual cursor for determining where in the stream the current position is The value of Position cannot be greater than the value of the stream's Length
Trang 24P Reading and Writing Files m Siream class Phương thức Name Description
Close Closes the stream and releases any resources associated with tt
Plush Clears any buffers within the stream and forces changes to be written to the underlying system or device
Read Performs a sequential read of a specified number of bytes from the current position and updates the position to the end of the read upon completion of the operation
Read Byte Performs the read of a single byte and updates the position by moving it by one Identical to calling Read to read a single byte
Sets the position within the stream
setLength |Specifies the length of the stream Will truncate the stream if the new length is less than the old length and will expand the stream if the reverse 1s true
Write Writes information to the stream as a number of bytes and updates the current position to reflect the new write position
Trang 25§) Reading and Writing Files FileStream class: ké thUfa Stream class Thuộc tính Name Description
Trang 26§) Reading and Writing Files
Stream Reader class
Kể thửa TextReader class
Dùng để đọc các file văn bản
Thuộc tính
Name Description
BasesStream Gets the underlying stream that the reader 1s reading Current#xucoding |Gets the current encoding used for the underlying
stream
Trang 27§) Reading and Writing Files
Stream Reader class
Phương thức
Name Description
Close Closes the reader and the underlying stream
Peek Returns the next character in the stream without moving the
stream's current position
Read Reads the next set of characters in the stream ReadBlock \Reads the next block of characters in the stream Readiine \Reads the next line of characters in the stream
Trang 28
ac: and Writing Files
= Doc file van ban
FileStream theFile = File.-Open(@"C:\boot.ini",
FileMode.Open, FileAccess Read);
Trang 29§) Reading and Writing Files
StreamWriter class
Kể thửa TextWriter class
Dùng để ghi các file văn bản
Thuộc tính
Name Description
AutoPlush \Gets or sets an indicator that shows whether every call to the Write method should flush changes to the underlying stream
SaseStream |Gets the underlying stream that the reader 1s reading Encoding |Gets the current encoding used for the underlying stream
Trang 30§) Reading and Writing Files
StreamWriter class
Phương thức
Name Description
Close Closes the writer and the underlying stream
Write Writes to the stream
Trang 31
ac: and Writing Files
» Vi du
„ Ghi file văn bản
Trang 32
ac: and Writing Files
=» BinaryReader class
= Dung dé doc file nhi phan
= Cung cap cac phuong thức có dạng
Trang 33ac: and Writing Files » Vi du s Đọc file nhị phân FileStream theFile = File.Coen(Œ@”c:\`somefile.bin”, FileMode.Open); BinaryReader reader = new BinaryReader(theFile) ; long number = reader.Readl nt64();
byte[] bytes = reader.ReadBytes(4) ;
Trang 34
ac: and Writing Files
=» BinaryWriter class
= Dung dé ghi file nhi phan
= Cung cap cac phương thức Write với nhiêu
dạng tham số khác nhau để ghi nội dung
Trang 35
ac: and Writing Files
» Vi du
a Ghi file nhi phan
FileStream theFile = File.Open(@"c:\somefile.bin",
FileMode.OpenOrCreate, FileAccess Write);
BinaryWriter writer = new
BIinaryWriter(theFile) ;
lòng number = 100;
byte[] bytes = new byte[] { 10, 20, 50, 100 };
string s= “Toi di hoc’; writer.Write(number);
writer Write(bytes);
Trang 36§) Reading and Writing Files MemoryStream class: kế thừa Stream class Thuộc tính Name Description Capacity |Gets or sets the number of bytes allocated for the stream Phương thức Name Description
CetSuffer Retrieves the array of unsigned bytes that were used to create the stream
Trang 37
ac: and Writing Files
MemoryStream memStrm = new MemoryStream();
Trang 38
ac: and Writing Files
=» BufferedStream class
Trang 39
he Streams
= Cho phép nén dữ liệu gốc tối đa là 4GB „ Kiểu nén: GZIP và DEFLATE
'N©-:|© lele ho tro
» GZipStream class
Trang 40
he Streams
=» GZipStream class
„ KẾ thừa Stream class
« Dùng để nén/giải nén tập tin theo GZIP
=» Neén tap ale
FileStream sourceFile = File OQoenRead(inFilename);
FileStream destFile = File.Create(outFilename) ;
GZipStream compStream = new GZipStream(sourceFile,
CompressionMode.Compress): byte[] Arr = new byte[4096];
int theByte = sourceFile.Read(Arr, 0, 4096);
while(theByte!= 0)
{
compstream.Write(Arr, 0, theByte) ;
Trang 41
he Streams
=» GZipStream class
= Giai nén tap tin
FileStream sourceFile = File OQoenRead(inFilename) ;
FileStream destFile = File.Create(outFilename) ;
GZipStream compStream = new
GZipStream(sourceFile,
CompressionMode.Decompress) ; byte[] Arr = new byte[4096] ;
int theByte = compStream.Read(Arr, 0, 4096);
while (theByte != 0)
|
destFile.Write(Arr, 0, theByte);
Trang 42
he Streams =» DeflateStream class
Kêt hợp giữa LZ77 và Huffman
Dùng tương tự như GZipStream class
Cho kích thước nén nhỏ hơn
File nén không thể mở được bằng các
Trang 43
=
Trang 44tring an ¬ ‘isting tile altermoartitrelt: re esa tho
string into an existing file, altematively creating the + + file if one does not exist) and retum 44 + + 4 to allow text to be appended to x* + _ Niet WH ot So - > ˆ w file The new file must not exist for Cop ce — ate w file and returns a rear object ~4 4 reates or opens a [lle and retums a 572đ??? Vrite text \vrift ? mt + SSL NS SLi st ~4 ~ + Moves a file from one placet tO anotner = “isting 1 1 vyatiiwmme Ts “*2/21?? hj +
Le? bun Co C2 sting i nd retums reciri ODIJect
cing Fil - 1 Bela Em existing fil retums a ream object
OsenR tveaởd , CG
~4 4 “ 4
acting file and retume teamReader obiect
€XISHHEB Tlie and retuims ¿7Ø? eqœec?ˆ ODIeCL ee existing f ‘ile for writing and returns a Stearn IT rite , z ds the contents of it into cS fụ xá ry w O O Op O O = ;
/ Moc ’ theaer hnreantc oS an
ReadAliLines _reads the contents of it into an
1?1 T12 2†/YTYI Operati
+'d aii 4i\% GL aiid lát
ReadAliText pe s the contents of it into
rns mene
e atomic operatlo +
~ 4 ee
,2 ~*vyvfayyftc + 4 White erat int + ‘arteritis ant
1€ contents Of a OVTe atray into lt (OVerwriting any
4 cac +1 b> 1 eh 1 ^ % rT yer «° 1 T1
1OS€S is asim S44 one at 4iad pe ROLLS a
+ + + Ế = - + +
tt th > hte - a1 TY24Y' 1 1 + tt +31 £1+) ant
- Writes The contents Of a String array into it (overv riting any
4 4 ~4
oses SC5 LIÁC Lil The TI + +1 ĐIC aT đ(OiIIIC 1 O|)CidLiOiI ¬>2^r2f†1 >3
~4 stante ~ ~ rin et TIKIT IY me ant