Tải bản đầy đủ (.ppt) (69 trang)

Chapter 13 - File IO and Isolated Storage pps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.23 MB, 69 trang )

Chapter 13. File I/O and
Isolated Storage
Hoang Anh Viet

Hanoi University of Technology
1
Microsoft
Objectives
“The System.IO namespace allows you to interact with a machine’s file
and directory structure. Over the course of this chapter, you will
learn how to programmatically create (and destroy) a directory
system as well as move data into and out of various streams (file
based, string based, memory based, etc.). The latter part of this
chapter examines the role of isolated storage, which allows you to
persist per-user data into a safe sandbox, regardless of the security
settings of a target machine. To understand certain aspects of the
System.IO.IsolatedStorage API, you will also receive an overview of
Code Access Security (CAS).…”
2
Microsoft
Roadmap
1. Exploring the System.IO namespace
2. Working with File System
3. The Abstract System Class
4. Working with StreamWriters and StreamReaders
5. Working with StringWriters and StringReaders
6. Working with BinaryWriters and BinaryReaders
7. Programmatically “Watching” Files
8. Performing Asynchronous File I/O
9. An Overview of Isolated Storage
10. Introducing Object Serialization


3
Microsoft
13.1 Exploring the System.IO namespace

System.IO namespace is the region of the base class
libraries devoted to file-based (and memory-based) input
and output (I/O) services

System.IO defines a set of classes, interfaces,
enumerations, structures, and delegates, most of which
are contained in mscorlib.dll
4
Microsoft
5
Nonabstract I/O Class
Type
Description
BinaryReader, BinaryWriter These types allow you to store and retrieve primitive data types
(integers, Booleans, strings, and whatnot) as a binary value.
BufferedStream This type provides temporary storage for a stream of bytes that may
be committed to storage at a later time
Directory, DirectoryInfo These types are used to manipulate a machine’s directory structure.
The Directory type exposes functionality using static members. The
DirectoryInfo type exposes similar functionality from a valid object
reference.
DriveInfo This type provides detailed information regarding the drives used by a
given machine.
File, FileInfo These types are used to manipulate a machine’s set of files. The File
type exposes functionality using static members. The FileInfo type
exposes similar functionality from a valid object reference.

FileStream This type allows for random file access (e.g., seeking capabilities)with
data represented as a stream of bytes.
Figure 13.1 Key Members of the System.IO Namespace
Microsoft
6
Nonabstract I/O Class
Type
Description
FileSystemWatcher This type allows you to monitor the modification of external files in a
specified directory.
MemoryStream This type provides random access to streamed data stored in memory
rather than a physical file.
Path This type performs operations on System.String types that contain file
or directory path information in a platform-neutral manner.
StreamWriter, StreamReader These types are used to store (and retrieve) textual information to (or
from) a file. These types do not support random file access.
StringWriter, StringReader Like the StreamReader/StreamWriter types, these classes also work
with textual information. However, the underlying storage is a string
buffer rather than a physical file.
Figure 13.1 Key Members of the System.IO Namespace (Cont.)
Microsoft
Roadmap
1. Exploring the System.IO namespace
2. Working with File System
3. The Abstract System Class
4. Working with StreamWriters and StreamReaders
5. Working with StringWriters and StringReaders
6. Working with BinaryWriters and BinaryReaders
7. Programmatically “Watching” Files
8. Performing Asynchronous File I/O

9. An Overview of Isolated Storage
10. Introducing Object Serialization
7
Microsoft
13.2 Working with File System

System.IO namespace include a few basic classes for
retrieving file system information

Directory and File: These classes provide static methods that
allow you to retrieve information about any files and directories
that are visible from your server

DriveInfo, DirectoryInfo, FileInfo: These classes use similar
instance methods and properties to retrieve the same
information



The simplest level of file access:

Involves retrieving information about existing files and
directories

Performing typical file system operations such as copying files
and creating directories
8
Microsoft
Classes File and Directory
9

Figure 13.2 The File- and Directory-centric types
Microsoft
10
Method Description
CreateDirectory() Creates a new directory. If you specify a directory inside
another nonexistent directory, ASP.NET will thoughtfully
create all the required directories.
Delete() Deletes the corresponding empty directory. To delete a directory
along with its contents (subdirectories and files), add the optional
second parameter of true.
Exists() Returns true or false to indicate whether the specified directory
exists.
GetCreationTime(),
GetLastAccessTime(),
and GetLastWriteTime()
Returns a DateTime object that represents the time the directory
was created, accessed, or written to. Each “Get” method has
a corresponding “Set” method, which isn’t shown in this table.
GetDirectories() and GetFiles() Returns an array of strings, one for each subdirectory or file in
the specified directory. These methods can accept a second
parameter that specifies a search expression (such as ASP*.*).
GetLogicalDrives() Returns an array of strings, one for each drive that’s defined
on the current computer. Drive letters are in this format: c:\.
Figure 13.3 Directory Methods
Microsoft
11
Method Description
GetParent() Parses the supplied directory string and tells you what
the parent directory is. You could do this on your own
by searching for the \ character (or, more generically, the

Path.DirectorySeparatorChar), but this function makes life a little
easier.
GetCurrentDirectory()
and SetCurrentDirectory()
Allows you to set and retrieve the current directory, which is useful if
you need to use relative paths instead of full paths. Generally, you
shouldn’t rely on these functions—use full paths instead.
Move() Accepts two parameters: the source path and the destination path.
The directory and all its contents can be moved to any path, as long as
it’s located on the same drive.
GetAccessControl() and
SetAccessControl()
Returns or sets a System.Security.AccessControl.Directory-
Security object. You can use this object to examine the
Windows access control lists (ACLs) that are applied on this directory
and even change them programmatically.
Figure 13.3 Directory Methods (Cont.)
Microsoft
12
Figure 13.4 File Methods
Method Description
Copy() Accepts two parameters: the fully qualified source filenameand the
fully qualified destination filename. To allow overwriting, use the
version that takes a Boolean third parameter and set it to true.
Delete() Deletes the specified file but doesn’t throw an exception if the file can’t
be found.
Exists() Indicates true or false whether a specified file exists.
GetAttributes()
and SetAttributes()
Retrieves or sets an enumerated value that can include any

combination of the values from the FileAttributes enumeration.
GetCreationTime(),
GetLastAccessTime(),
and GetLastWriteTime()
Returns a DateTime object that represents the time the file
wascreated, accessed, or last written to. Each “Get” method has a
corresponding “Set” method, which isn’t shown in this table.
Move() Accepts two parameters: the fully qualified source filename and the
fully qualified destination filename. You can move a file across drives
and even rename it while you move it (or rename it without moving it).
Microsoft
13
Method Description
Create() and CreateText() Creates the specified file and returns a FileStream object that you can
use to write to it. CreateText() performs the same task but returns a
StreamWriter object that wraps the stream.
Open(), OpenText(),
OpenRead(), and OpenWrite()
Opens a file (provided it exists). OpenText() and OpenRead() open a
file in read-only mode, returning a FileStream or StreamReader.
OpenWrite() opens a file in write-only mode, returning a FileStream.
ReadAllText(),
ReadAllLines(),
and ReadAllBytes()
Reads the entire file and returns its contents as a single string, an
array of strings (one for each line), or an array of bytes. Use this
method only for very small files. For larger files, use streams to read
one chunk at a time and reduce the memory overhead.
WriteAllText(), WriteAllLines(),
and WriteAllBytes()

Writes an entire file in one shot using a supplied string, array of strings
(one for each line), or array of bytes. If the file already exists, it is
overwritten.
GetAccessControl()
and SetAccessControl()
Returns or sets a System.Security.AccessControl.FileSecurity
object. You can use this object to examine the Windows ACLs that are
applied on this directory and even change them programmatically.
Figure 13.4 File Methods (Cont.)
14
Example 13.1 Displaying the name of each file in the current directory
15
16
Example
Microsoft
The DirectoryInfo and FileInfo Classes

Mirror the functionality in the Directory and File
classes

Share a common set of properties and methods
because they derive from the common
FileSystemInfo base class
17
Microsoft
18
Figure 13.5 DirectoryInfo and FileInfo Members
Method Description
Attributes Allows you to retrieve or set attributes using a combination of values fromthe
FileAttributes enumeration.

CreationTime,
LastAccessTime,
and LastWriteTime
Allows you to set or retrieve the creation time, last access time, and last write
time using a DateTime object.
Exists Returns true or false depending on whether the file or directory exists. In other
words, you can create FileInfo and DirectoryInfo objects that don’t actually
correspond to current physical directories, although you obviously won’t be
able to use properties such as CreationTime and methods such as MoveTo().
FullName, Name,
and Extension
Returns a string that represents the fully qualified name, the directory or
filename (with extension), or the extension on its own, depending on which
property you use.
Delete() Removes the file or directory, if it exists. When deleting a directory, it must be
empty, or you must specify an optional parameter set to true.
Refresh() Updates the object so it’s synchronized with any file system changes that have
happened in the meantime (for example, if an attribute was changed manually
using Windows Explorer).
Create() Creates the specified directory or file.
MoveTo() Copies the directory and its contents or the file. For a DirectoryInfo object, you
need to specify the new path; for a FileInfo object, you specify a path and
filename.
Microsoft
19
Figure 13.6 Unique DirectoryInfo Members
Method Description
Parent and Root Returns a DirectoryInfo object that represents the parent or root directory.
CreateSubdirectory(
)

Creates a directory with the specified name in the directory represented
by the DirectoryInfo object. It also returns a new DirectoryInfo object
that represents the subdirectory.
GetDirectories() Returns an array of DirectoryInfo objects that represent all the subdirectories
contained in this directory.
GetFiles() Returns an array of FileInfo objects that represent all the files contained
in this directory.
Microsoft
20
Figure 13.7 Unique FileInfo Members
Method Description
Directory Returns a DirectoryInfo object that represents the parent directory.
DirectoryName Returns a string that identifies the name of the parent directory.
Length Returns a long (64-bit integer) with the file size in bytes.
CopyTo() Copies a file to the new path and filename specified as a parameter. It
also returns a new FileInfo object that represents the new (copied) file.
You can supply an optional additional parameter of true to allow
Overwriting.
Create() and
CreateText()
Creates the specified file and returns a FileStream object that you can
use to write to it. CreateText() performs the same task but returns a
StreamWriter object that wraps the stream.
Open(),
OpenRead(),
OpenText(), and
OpenWrite()
Opens a file (provided it exists). OpenRead() and OpenText() open a file in
read-only mode, returning a FileStream or StreamReader. OpenWrite()
opens a file in write-only mode, returning a FileStream.

Microsoft
The DirectoryInfo and FileInfo Classes

Constructor

When create a new DirectoryInfo or FileInfo object

Receive an exception if the path you used isn’t properly formed

use Exists to check whether directory or file really exists

If doesn’t exist, use a method such as Create() to create it
21
Microsoft
The DriveInfo Class

Retrieve information about a drive on your
computer

DriveInfo class is merely used to retrieve the
total amount of used and free space
22
Microsoft
23
Method Description
TotalSize Gets the total size of the drive, in bytes. This includes allocated and
free space.
TotalFreeSpace Gets the total amount of free space, in bytes.
AvailableFreeSpace Gets the total amount of available free space, in bytes. Available space
may be less than the total free space if you’ve applied disk quotas limiting

the space that the ASP.NET process can use.
DriveFormat Returns the name of the file system used on the drive (such as NTFS
or FAT32).
DriveType Returns a value from the DriveType enumeration, which indicates
whether the drive is a fixed, network, CD-ROM, RAM, or removable drive.
(It returns Unknown if the drive’s type cannot be determined.)
IsReady Returns whether the drive is ready for reading or writing operations.
Removable drives are considered “not ready” if they don’t have any
media. For example, if there’s no CD in a CD drive, IsReady will return
false. In this situation, it’s not safe to query the other DriveInfo properties.
Fixed drives are always readable.
Figure 13.8 DriveInfo Members
Microsoft
24
Method Description
Name Returns the drive letter name of the drive (such as C: or E:).
VolumeLabel Gets or sets the descriptive volume label for the drive. In an NTFSformatted
drive, the volume label can be up to 32 characters. If not set, this property
returns null.
RootDirectory Returns a DirectoryInfo object for the root directory in this drive.
GetDrives() Retrieves an array of DriveInfo objects, representing all the logical drives
on the current computer.
Figure 13.8 DriveInfo Members (Cont.)
25
Example 13.2 Sample File Browser

×