1. Trang chủ
  2. » Vật lí lớp 11

this site is individual site for ueh students of information management faculty this site provides some students resources of it courses such as computer network data structure and algorithm enterprise resource planning

69 8 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 69
Dung lượng 560,59 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

 The BinaryWriter class defines a highly overloaded Write() method to place a data type in the underlying stream.. Microsoft[r]

Trang 1

Chapter 13 File I/O and

Isolated Storage

Trang 2

Objectives

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 3

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

Trang 4

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

Trang 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 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

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

Trang 6

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.)

Trang 7

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

Trang 8

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

Trang 9

Classes File and Directory

Figure 13.2 The File- and Directory-centric types

Trang 10

Microsoft 10

Method Description

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 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 Security object You can use this object to examine theWindows access control lists (ACLs) that are applied on this directory and even change them programmatically

System.Security.AccessControl.Directory-Figure 13.3 Directory Methods (Cont.)

Trang 12

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

“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)

Trang 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

Figure 13.4 File Methods (Cont.)

Trang 14

using System IO ;

public partial class ViewFiles : System Web UI Page

{

private string ftpDirectory ;

protected void Page_Load ( Object sender , EventArgs e )

private void CreateFileList ()

{

// Retrieve the list of files, and display it in the page.

// This code also disables the delete button, ensuring the

// user must view the file information before deleting it.

string [] fileList = Directory GetFiles ( ftpDirectory );

Trang 15

protected void cmdRefresh_Click ( Object sender , EventArgs e )

// Display the selected file information.

// Use the StringBuilder for the fastest way to build the string.

string fileName = lstFiles SelectedItem Text ;

displayText Append ( "<b>" );

displayText Append ( "</b><br /><br />" );

displayText Append ( "<br />" );

// Show attribute information GetAttributes() can return a combination

// of enumerated values, so you need to evaluate it with the

// bitwise and (&) operator.

Trang 16

if (( attributes & FileAttributes Hidden ) == FileAttributes Hidden )

// Show the generated text in a label.

Trang 17

The DirectoryInfo and FileInfo Classes

classes

because they derive from the common

FileSystemInfo base class

Trang 18

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

Trang 19

Figure 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 20

Microsoft 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 21

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

// Define the new directory and file.

// Now create them Order here is important.

// You can't create a file in a directory that doesn't exist yet.

Trang 22

The DriveInfo Class

computer

total amount of used and free space

22

Trang 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 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.)

IsReady Returns whether the drive is ready for reading or writing operations

Removable drives are considered “not ready” if they don’t have anymedia For example, if there’s no CD in a CD drive, IsReady will returnfalse In this situation, it’s not safe to query the other DriveInfo properties

Fixed drives are always readable

Figure 13.8 DriveInfo Members

Trang 24

Microsoft 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 25

public partial class FileBrowser : System Web UI Page

private void ShowFilesIn ( string dir )

{

try

{

foreach ( FileInfo fileItem in dirInfo GetFiles ()) {

} }

Example 13.2 Sample File Browser

Trang 26

catch ( Exception err ) {

// Ignore the error and leave the list box empty.

} }

private void ShowDirectoriesIn ( string dir )

{

try

{

foreach ( DirectoryInfo dirItem in dirInfo GetDirectories ()) {

} }

catch ( Exception err ) {

// Ignore the error and leave the list box empty.

} }

protected void cmdBrowse_Click ( Object sender , EventArgs e )

{

// Browse to the currently selected subdirectory.

26

Trang 27

if ( lstDirs SelectedIndex != - 1 )

{

string newDir = Path Combine ( lblCurrentDir Text ,

} }

protected void cmdParent_Click ( object sender , EventArgs e )

{

// Browse up to the current directory's parent.

// The Directory.GetParent() method helps us out.

string newDir = Directory GetParent ( lblCurrentDir Text ) FullName ;

} }

Trang 28

protected void cmdShowInfo_Click ( object sender , EventArgs e )

{

// Show information for the currently selected file.

if ( lstFiles SelectedIndex != - 1 )

{

string fileName = Path Combine ( lblCurrentDir Text ,

lstFiles SelectedItem Text );

StringBuilder displayText = new StringBuilder ();

try

{

FileInfo selectedFile = new FileInfo ( fileName );

displayText Append ( "<b>" );

displayText Append ( selectedFile Name );

displayText Append ( "</b><br />Size: " );

displayText Append ( selectedFile Length );

displayText Append ( "<br />" );

displayText Append ( "Created: " );

displayText Append ( selectedFile CreationTime ToString ());

displayText Append ( "<br />Last Accessed: " );

displayText Append ( selectedFile LastAccessTime ToString ());

Trang 29

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

Trang 30

13.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 31

Figure 13.9 Stream-derived types

Trang 32

Microsoft 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 33

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

Trang 34

13.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

Ngày đăng: 25/01/2021, 13:28

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm

w