BufferedStream This type provides temporary storage for a stream of bytes that may be committed to storage at a later timeDirectory, DirectoryInfo These types are used to manipulate a ma
Trang 1Chapter 13 File I/O and
Isolated Storage
Hoang Anh Viet
Trang 2Objectives
“ 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
Trang 31 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
Trang 413.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
Trang 5Nonabstract I/O Class
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 timeDirectory, 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
Figure 13.1 Key Members of the System.IO Namespace
Trang 6MemoryStream 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.)
Trang 71 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
Trang 813.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
Trang 9Classes File and Directory
Trang 10Microsoft 10
CreateDirectory() Creates a new directory If you specify a directory inside
another nonexistent directory, ASP.NET will thoughtfullycreate 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
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 secondparameter 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
Trang 11Method 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 Security object You can use this object to examine theWindows access control lists (ACLs) that are applied on this directory
System.Security.AccessControl.Directory-Figure 13.3 Directory Methods (Cont.)
Trang 12Microsoft 12
Figure 13.4 File Methods
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
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)
Trang 13Method 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
Trang 14Example 13.1 Displaying the name of each file in the current directory
Trang 16Example
Trang 17The 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
Trang 18Exists 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
Trang 19Figure 13.6 Unique DirectoryInfo Members
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 objectthat 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
Trang 20Microsoft 20
Figure 13.7 Unique FileInfo Members
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 allowOverwriting
Create() and
CreateText()
Creates the specified file and returns a FileStream object that you canuse to write to it CreateText() performs the same task but returns aStreamWriter object that wraps the stream
Trang 21The 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
Trang 22The 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
Trang 23Method 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 limitingthe 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.)
Figure 13.8 DriveInfo Members
Trang 24Microsoft 24
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.)
Trang 25Example 13.2 Sample File Browser
Trang 2626
Trang 291 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
Trang 3013.3 The Abstract System Class
A stream represents a chunk of data flowing between a
source and a destination.
Streams provide a common way to interact with a
sequence of bytes, regardless of what kind of device
(file, network connection, printer, etc.) is storing or
displaying the bytes in question.
The abstract System.IO.Stream class defines a number
of members that provide support for synchronous and asynchronous interactions with the storage medium
The FileStream class provides an implementation for the abstract Stream members in a manner appropriate for file-based streaming
30
Trang 32Microsoft 32
CanRead, CanWrite Determine whether the current stream supports reading, seeking, and/or
CanSeek writing
Close() Closes the current stream and releases any resources (such as sockets and
file handles) associated with the current stream Internally, this method is aliased to the Dispose() method; therefore “closing a stream” is functionally equivalent to “disposing a stream.”
Flush() Updates the underlying data source or repository with the current state of the
buffer and then clears the buffer If a stream does not implement a buffer, this method does nothing
Length Returns the length of the stream, in bytes
Position Determines the position in the current stream
Read(), ReadByte() Read a sequence of bytes (or a single byte) from the current stream and
advance the current position in the stream by the number of bytes read
Seek() Sets the position in the current stream
SetLength() Sets the length of the current stream
Write(), WriteByte() Write a sequence of bytes (or a single byte) to the current stream and
advance the current position in this stream by the number of bytes written
Figure 13.10 Abstract Stream Members
Trang 331 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
Trang 3413.4 Working with StreamWriters and
StreamReaders
The StreamWriter and StreamReader classes are useful
to read or write character-based data (e.g., strings)
Both of these types work by default with Unicode characters
StreamReader derives from an abstract type named
TextReader
The TextReader base class provides a very limited set of
functionality to each of these descendents, specifically the ability
to read and peek into a character stream
The StreamWriter type derives from an abstract base
class named TextWriter
This class defines members that allow derived types to write
textual data to a given character stream
34
Trang 35Member Meaning in Life
Close() This method closes the writer and frees any associated resources In the
process,the buffer is automatically flushed (again, this member is functionally equivalent to calling the Dispose() method)
Flush() This method clears all buffers for the current writer and causes any buffered
data to be written to the underlying device, but does not close the writer
NewLine This property indicates the newline constant for the derived writer class The
default line terminator for the Windows OS is a carriage return followed by a line feed (\r\n)
Write() This overloaded method writes data to the text stream without a newline
constant
WriteLine() This overloaded method writes data to the text stream with a newline constant
Figure 13.11 Core Members of TextWriter