a 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
Trang 1Input/Output with
m NET Framework Class Library
Pham Minh Tuan
BỘ môn CNPM — Khoa CNTT
Trang 2
a a dung trinh bay
=» Navigating the File System
=» Reading and Writing Files
=» Compressing Streams
Trang 5DriveFormat 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
Gets or sets the label of the drive It might be set only on drives that are not readonly
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 CetDrives |A static method (or a shared one in Visual Basic) that returns
allthe drives on the current system
Trang 7Attributes 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
Name Gets the simple name for the file or directory For a file, this is the name
within the directory For a directory, this is the last directory name in the directory hierarchy
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
system
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
Root |Gets the root part of the directory's path as a string
Trang 10Lirectorylnfo 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
Moves the current directory to a new location
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
LirectoryName \Gets the name ofthe directory that this file is stored
Trang 12CapyTo 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
Replaces a file with the information in the current Pile/nfo object
Trang 13changes, 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
Returns a full path to the specified path This method can
be used to resolve relative paths
Trang 14GetTempPileName
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
Indicates whether the specified path includes a root directory
Trang 15
a Navigating the File System
|
FileSystemWatcher class Thuộc tính
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
Gets or sets the path to the directory to monitor
Trang 16Navigating the File System
FileSystemWatcher class Phương thức
WaithorChanged |Synchronous method for watching a directory for changes and for
returning a structure that contains all the changes
Su kiện
Name (|Description Changed |Occurs when a file or directory has changed in the watched directory Created |Occurs when a file or directory has been created in the watched directory Deleted \Occurs when a file or directory has been deleted in the watched directory Renamed |Occurs when a file or directory has been renamed in the watched directory
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}",
drive.DriveType) ;
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 đó?
Directorylnfo ourDir = new
Trang 19
a the File System
m Làm sao truy xuất được các thuộc tính của mội tập tin, thư mục?
Filelnfo ourFile = new Filelnfo(@"c:\boot.ini ");
Trang 20
a the File System
= Lam sao giam sat được sự thay đổi của một tập tin, thư mục?
FilesystemWatcher watcher = new FileSystemWatcher();
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ị chuyển thư mục, lấy danh sách tập tin, thư mục con
Trang 22ac: and Writing Files
=» Stream class
=» FileStream class
» StreamReader class, StreamWriter class
» BinaryReader class, BinaryWriter class
» Memorystream class
» BufferedStream class
Trang 23CanSeek 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
ReadTimeout |Gets or sets the stream's timeout for read operations
Write Timeout |Gets or sets the stream's timeout for write operations
Trang 24Plush 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
WriteByte |Writes a single byte to the stream and updates the position Identical to calling
Write with a single byte
Trang 25§) Reading and Writing Files
FileStream class: ké thUfa Stream class
Thuộc tính Name Description Handle Gets the stream's underlying file handle
Name Gets the name of the file
Phương thức Name Description Lock Prevents other processes from changing all or part of the
file
Unlock Allows other processes to change all or part of the
underlying file.
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
EndOfstream Determines whether the reader has encountered the end
of the 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 Read loHnd \Reads all the characters through to the end of the stream
Trang 28
ac: and Writing Files
= Doc file van ban
FileStream theFile = File.-Open(@"C:\boot.ini",
FileMode.Open, FileAccess Read);
Stream Reader rdr = new StreamReader(theFile) ; while (!rdr.EndOfStream)
string line = rdr.ReadLine();
Console.WriteLine(line) ;
} rdr.Close();
theFile.Close();
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
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
Newline — |Gets or sets a string that contains the line terminator string Normally used
only if you need to change the string that terminates an individual line.
Trang 30§) Reading and Writing Files
StreamWriter class
Phương thức
Close Closes the writer and the underlying stream
WriteLine |\Writes data to the stream followed by the string that
terminates an individual line
Trang 31
ac: and Writing Files
» Vi du
„ Ghi file văn bản
FileStream theFile = File.COpoen(Œ@”c:\somefile.tx{”,
Trang 32
ac: and Writing Files
=» BinaryReader class
= Dung dé doc file nhi phan
= Cung cap cac phuong thức có dạng ReadXxXx(ReadByte, ReadInt32 ) dé doc noi dung file
Trang 33byte[] bytes = reader.ReadBytes(4) ;
string s = reader.ReadString();
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
II:
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);
writer.Write(s);
Trang 36§) Reading and Writing Files
Phương thức
Name Description
CetSuffer Retrieves the array of unsigned bytes that were used to
create the stream
foArray |Writes the entire stream to an array of bytes
Writefo \Writes the MemoryStream to another stream.
Trang 37
ac: and Writing Files
MemoryStream memStrm = new MemoryStream();
StreamWriter writer = new StreamWriter(memStrm) ; writer WriteLine("Hello") ;
Trang 38
ac: and Writing Files
=» BufferedStream class
= Thuong dung cho NetworkStream
= Tang hiéu qua doc/ghi du liệu
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
=» DeflateStream 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) ; theByte = sourceFile.Read(Arr, 0, 4096);
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);
theByte = compsStream.Read(Arr, 0, 4096);