Microsoft .NET Framework 2.0 Application Development Foundation 翻译系列9(第二章 I/O:第一课 文件系统操作)

 

Chapter 2: Input/Output (I/O)

Overview

In this chapter, you will learn how to work with the input/output (I/O) system within the Microsoft .NET Framework. The basics of the I/O system include accessing files and folders in the file system, working with read and write streams, using compression streams, and using isolated storage.

概述

本章中,你将学习如何使用.NET 框架中的input/output(I/O)系统进行开发.I/O系统的基础包括了访问文件系统中的文件和目录,读写流的使用,利用压缩流和利用隔离存储.

Exam objectives in this chapter: 本章考试目标

·         Access files and folders by using the File System classes. (Refer System.IO namespace)

o        File class and FileInfo class

o        Directory class and DirectoryInfo class

o        DriveInfo class and DriveType enumeration

o        FileSystemInfo class and FileSystemWatcher class

o        Path class

o        ErrorEventArgs class and ErrorEventHandler delegate

o        RenamedEventArgs class and RenamedEventHandler delegate

·         利用文件系统类访问文件和目录(引用System.IO命名空间)

o        FileFileInfo

o        DirectoryDirectoryInfo

o        DriveInfo类和DriveType枚举类型

o        FileSystemInfoFileSystemWatcher

o        Path

o        ErrorEventArgs类和ErrorEventHandler委托类

o        RenamedEventArgs类和RenameEventHandler委托类

·         Manage byte streams by using Stream classes. (Refer System.IO namespace)

o        FileStream class

o        Stream class (not Reader and Writer classes because they are a separate objective)

o        MemoryStream class

o        BufferedStream class

·         利用Stream类来管理byte(引用System.IO命名空间)

o        FileStream

o        Stream(不是ReaderWriter,因为它们是一个单独的考试目标)

o        MemoryStream

o        BufferedStream

·         Manage the .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace)

o        StringReader class and StringWriter class

o        TextReader class and TextWriter class

o        StreamReader class and StreamWriter class

o        BinaryReader class and BinaryWriter class

·         利用ReaderWriter类来管理.NET框架应用程序数据

o        StringReaderStrngWriter

o        TextReaderTextWriter

o        StreamReaderStreamWriter

o        BinaryReaderBinaryWriter

·         Compress or decompress stream information in a .NET Framework application (refer System.IO.Compression namespace) and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace)

o        IsolatedStorageFile class

o        IsolatedStorageFileStream class

o        DeflateStream class

o        GZipStream class

·         .NET框架应用程序中压缩和解压缩流的情况(引用System.IO.Compression命名空间),并利用隔离存储(isolated storage)来改善应用程序数据安全性.(引用System.IO.IsolatedStorage命名空间)

Before You Begin

To complete the lessons in this chapter, you should be familiar with Microsoft Visual Basic or C# and be comfortable with the following tasks:

完成本章中的课程,你将熟练的使用VB/C#,并轻松的完成下面的任务.

  • Create a console application in Microsoft Visual Studio using Visual Basic or C#.
  • Add references to system class libraries to a project.
  • Create text files.
  • 利用VB/C#建立一个控制台应用程序
  • 为一个项目添加系统类库的引用
  • 建立文本文件

Real World

Shawn Wildermuth

I've written hundreds, if not thousands, of lines of code and invariably I come back to the I/O system for lots of it. The I/O section of the .NET Framework provides help for doing a myriad of tasks. Much of what is in the I/O system is the basis for other parts of the Framework as well as for third-party products. Learning the basics of how streams and files work has made doing my job much easier.

真实世界

我总是要为I/O系统编写上千行或上百行的代码.而.NET框架中的I/O部分为执行数以万计的任务提供了帮助.框架和第三方产品都是基于I/O系统的基础上.学习流和文件的基础,可以使我的工作更加轻松.

 

 


Lesson 1: Navigating the File System

第一课:文件系统操作

In the everyday work of developers, one of the most common tasks is to work with the file system. This task includes navigating and gathering information about drives, folders, and files as well as waiting for changes to happen in the file system.

在开发人员的每天工作中,一个最常见的任务就是使用文件系统工作.这项任务包括操作并收集设备,目录和文件的信息,这也包含了等待文件系统的变化.

 

After this lesson, you will be able to:

课后,你将能够:

·         Write code that uses the File and FileInfo classes.

·         Write code that uses the Directory and DirectoryInfo classes.

·         Use the DriveInfo and DriveType classes.

·         Enumerate files, directories, and drives using the FileSystemInfo derived classes.

·         Use the Path class to manipulate file system paths.

·         Watch for changes in the file system using the FileSystemWatcher class.

·         使用FileFileINfo类编写代码

·         使用DirectoryDirectoryInfo类编写代码

·         使用DriveInfoDriveType

·         使用FileSystemInfo列举文件,目录和设备

·         使用Path类熟练操作文件系统路径

·         利用FileSystemWatcher类查看文件系统的变化

 

Estimated lesson time: 20 minutes 课时20分钟

 

What Are the File System Classes?

Inside the System.IO namespace are a set of classes used to navigate and manipulate files, directories, and drives. The file system classes are separated into two types of classes: informational and utility.

System.IO命名空间中包括了一系列类,它们用来熟练操作文件,目录和设备.文件系统类分为两种: informational and utility

Most of the informational classes derive from the FileSystemInfo base class. These classes expose all the system information about file system objects—specifically, files, directories, and drives. These classes are named FileInfo and DirectoryInfo.

Informational类大部分都派生于FileSystemInfo基类.这些类提供了所有关于文件系统对象的系统信息,特定的,文件,目录和设备.这些类被命名为FileINfoDirectoryInfo

In addition, the DriveInfo class represents a drive in the file system, but although it is still an informational class, it does not derive from the FileSystemInfo class because it does not share the common sorts of behavior (for example, you can delete files and folders, but not drives).

另外,DriveInfo类代表文件系统中的一个设备,虽然它是一个informational,但它不派生于FileSystemInfo,因为它没有共享公共行为(例如,你可用删除文件和目录,但不能删除驱动器)

The utility classes provide static methods (or shared ones for Visual Basic) to perform certain operations on file system objects such as files, directories, and file system paths. These utility classes include the File, Directory, and Path classes.

Utility类提供静态方法(或与VB共享一个)对文件系统对象执行特定操作,例如文件,目录和文件系统路径.这些Utility类包括File,DirectoryPath

The FileSystemInfo Class

The FileSystemInfo class provides the basic functionality for all informational file system classes. Table 2-1 shows the most important FileSystemInfo properties.

FileSystemInfo类为所有informational文件系统类提供了基本功能.2-1显示了大部分重要的FileSystemInfo 属性(properties).

Table 2-1: FileSystemInfo Properties

Name

Description

Attributes

Gets or sets FileAttributes of the current file or directory.

获取或设置当前文件或目录的FileAttributes

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.

获取文件或目录扩展名字符串

FullName

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.

获取文件或目录的简称.对于文件,是在目录中的名称.对于目录是层次最低的目录名称

Table 2-2 shows the most important FileSystemInfo methods.

2-2展示FileSystemInfo大部分重要方法

Table 2-2: FileSystemInfo Methods

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

更新类中的数据信息.

The FileInfo Class

The FileInfo class provides the basic functionality to access and manipulate a single file in the file system.

FileInfo类提供访问和处理单个文件的基本功

Table 2-3 shows the most important FileInfo properties.

2-3展示大部分重要的FileInfo properties

Table 2-3: FileInfo Properties

Name

Description

Directory

Gets the DirectoryInfo object that represents the directory that this file is stored within

获取文件存储目录的DirectoryInfo对象

DirectoryName

Gets the name of the directory that this file is stored within

获取文件存储目录名称

IsReadOnly

Gets or sets the flag that dictates whether the file can be modified or deleted

获取或设置文件是否可以修改或删

Length

Gets the length of the file

获取文件长度

Table 2-4 shows the most important FileInfo methods.

2-4展示大部分重要的fileInfo方法

Table 2-4: FileInfo Methods

Name

Description

AppendText

Creates a new StreamWriter that will allow appending text to the file. See Lesson 2 for more information.

建立一个新的StreamWriter,它可以向文件追加文本数据.更多信息参考Lesson 2

CopyTo

Makes a copy of the file in a new location.

将一个文件复制到一个新的位置

Create

Creates a file based on the current file information.

基于当前文件信息建立一个新的文

CreateText

Creates a new StreamWriter and a new file for writing text. See Lesson 2 for more information.

建立一个新的StreamWriter和一个用来写入数据的新文件

Decrypt

Decrypts a file that was encrypted by the current user.

解密被当前用户加密的文件

Encrypt

Encrypts a file so that only the current user can decrypt the information within the file.

加密文件,只有当前用户能够解密这个文件信息.

MoveTo

Moves the file to a new location.

将文件移动到一个新的位置

Open

Opens the file with specific privileges (read, read/write, and so on).

用指定方式打开文件.(,/,)

OpenRead

Opens the file with read-only access.

用只读方式打开文件

OpenText

Opens the file and returns a StreamReader to allow reading of text within the file.

打开文件并返回一个StreamReader,它可以读取文件文本信息

OpenWrite

Opens the file with write-only access.

以只写放松打开文件

Replace

Replaces a file with the information in the current FileInfo object.

使用当前FileInfo对象中的信息替换一个文件

How to Get Information about a File

如何获取一个文件的信息

To obtain information about a specific file, follow this procedure:

对于获取一个特定文件的信息,参看下面的程序

·         Create a new FileInfo object by using the path to the file.

·         Access the FileInfo object's properties.

·         利用文件路径参数,建立一个新的FileInfo对象

·         访问FileInfo对象的属性(properties)

For example, you can check whether a file exists by calling the FileInfo object's Exist property, as shown in the following code:

例如,通过调用FileInfo对象的Exist属性,你能够检查一个文件是否存在.如下所示:

' VB
Dim ourFile As FileInfo = New FileInfo("c:\boot.ini")
 
If ourFile.Exists Then
    Console.WriteLine("Filename : {0}", ourFile.Name)
    Console.WriteLine("Path     : {0}", ourFile.FullName)
End If
 
// C#
FileInfo ourFile = new FileInfo(@"c:\boot.ini ");
 
if (ourFile.Exists)
{
    Console.WriteLine("Filename : {0}", ourFile.Name);
    Console.WriteLine("Path     : {0}", ourFile.FullName);
}

Using the FileInfo object this way allows code to interrogate the information about a file in the file system.

通过FileInfo对象可以编写代码查询文件系统中一个文件的信息.

How to Copy a File

如何复制一个文件

In addition to accessing data about a file, the FileInfo object allows operations to be performed on the file. Again, once a valid FileInfo object is obtained, all you have to do is call the CopyTo method to make a copy of your file, as the following code example shows:

关于访问一个文件的数据,通过FileInfo对象操作文件.使用曾经获取的一个有效的FileInfo对象,你可以调用CopyTo方法来复制你的文件.

' VB
Dim ourFile As FileInfo = New FileInfo("c:\boot.ini")
 
ourFile.CopyTo("c:\boot.bak")
 
// C#
FileInfo ourFile = new FileInfo(@"c:\boot.ini");
 
ourFile.CopyTo(@"c:\boot.bak");
 

The same procedure is used for moving and creating files. Once you have a valid FileInfo object, you can access all its properties and call any of its methods.

相同的过程,也可以用于移动和建立文件.你拥有一个有效FileInfo对象,你就能够访问它的所有属性和任意方法

The DirectoryInfo Class

The DirectoryInfo class provides the basic functionality to access and manipulate a single directory in the file system. Table 2-5 shows the most important DirectoryInfo properties.

DirectoryInfo类提供了访问和处理单一目录的基本功能.2-5展示了大部分重要的DirectoryInfo属性

Table 2-5: DirectoryInfo Properties

Name

Description

Parent

Gets the DirectoryInfo object for the parent directory of the current directory in the directory hierarchy

获取当前目录的父目录DirectoryInfo对象

Root

Gets the root part of the directory's path as a string

获取目录路径的根路径部分.

Table 2-6 shows the most important DirectoryInfo methods.

Table 2-6: DirectoryInfo Methods

Name

Description

Create

Creates the directory described in the current DirectoryInfo object

在当前DirectoryInfo对象中建立目录描述.

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

获取当前目录下的子目录信息的DirectoryInfo数组

GetFiles

Retrieves an array of FileInfo objects that represent all the files in the current directory

获取当前目录中所有文件信息的FileInfo对象数组

GetFileSystemInfos

Retrieves an array of FileSystemInfo objects that represent both files and subdirectories in the current directory

获取当前目录中文件和目录信息的FileSystemInfo对象数组

MoveTo

Moves the current directory to a new location

移动当前目录到一个新的位置

How to Enumerate Files in a Directory

如何列举出目录中的文件

Accessing the files in a directory is much like accessing file information. The following steps show how to enumerate the files in a directory:

访问目录中的文件很像访问文件信息.下面步骤显示了如何列举目录中的文件:

1.    Create a valid DirectoryInfo object by using the path to the directory.

2.    Call the GetFiles method to enumerate the files in the directory.

1.    通过目录路径来建立一个有效的DirectoryInfo对象

2.    调用GetFiles方法列举目录中的文件信息.

The following code example shows how to accomplish this task:

下面例子代码显示如何完成这个任务.

' VB
Dim ourDir As DirectoryInfo = New DirectoryInfo("c:\windows")
 
Console.WriteLine("Directory: {0}", ourDir.FullName)
 
Dim file As FileInfo
For Each file In ourDir.GetFiles()
    Console.WriteLine("File: {0}", file.Name)
Next
 
// C#
DirectoryInfo ourDir = new DirectoryInfo(@"c:\windows");
 
Console.WriteLine("Directory: {0}", ourDir.FullName);
 
foreach (FileInfo file in ourDir.GetFiles())
{
    Console.WriteLine("File: {0}", file.Name);
}

By using the GetFiles method of the DirectoryInfo object, you are able to enumerate through the files within a single directory.

通过使用DirectoryInfo对象中的GetFiles方法,你能够列举单个目录中的所有文件.

The DriveInfo Class

The DriveInfo class provides the basic functionality to access and manipulate a single directory in the file system. Table 2-7 shows the most important DriveInfo properties.

DriveInfo类提供了访问和处理单独设备的基本功能.2-7展示了大部分重要的属性

Table 2-7: DriveInfo Properties

Name

Description

AvailableFreeSpace

Gets the amount of available space on the drive. The amount might be different from the amount returned by TotalFreeSpace (described later in this table), depending on disk quotas.

获取驱动器可用磁盘空间总合.它可能与依靠磁盘限额的TotalFreeSpace返回的值不同,

DriveFormat

Gets the format of the drive, such as NTFS or FAT32.

获取驱动器格式,例如NTFSFAT32

DriveType

Gets the type of drive in the form of the DriveType enumeration (which is described in the following section).

获取驱动器类型的DriveType枚举格式

IsReady

Gets the status of the drive, indicating whether it is ready to be accessed.

获取驱动器状态,即它是否已准备好被访问的标志.

Name

Gets the name of the drive.

获取驱动器名称

RootDirectory

Gets a DirectoryInfo object that represents the root directory of the drive.

获取一个DirectoryInfo对象,它代表驱动器中的根目

TotalFreeSpace

Gets the total amount of free space on the drive.

获取驱动器中自由空间汇总值.

TotalSize

Gets the total size of the drive.

获取驱动器总空间

VolumeLabel

Gets or sets the label of the drive. It might be set only on drives that are not readonly.

获取或设置驱动器标签.它可能为驱动器设置,并且驱动器不能为只读.

Table 2-8 shows the most important DriveInfo method.

Table 2-8: DriveInfo Method

Name

Description

GetDrives

A static method (or a shared one in Visual Basic) that returns all the drives on the current system.

静态方法,返回当前系统所有驱动器.

The DriveType Enumeration

The DriveType enumeration provides the possible types of drives that can be represented by a DriveInfo object. Table 2-9 shows the members of the DriveType enumeration.

DriveType枚举类型提供了能够通过一个DriveInfo对象表示的驱动器的可能类型.2-9展示了DriveType的成员.

Table 2-9: DriveType Members

Name

Description

CDRom

An optical drive. It can be CD-ROM, DVD, and so on.

一个光驱设备.它可以是CD-ROM, DVD

Fixed

A fixed disk.

一个固定磁盘.

Network

A network mapped drive.

一个网络映射设备

NoRootDirectory

A drive that does not have a root directory.

一个不包含根目录的设备

Ram

A RAM drive.

一个闪存设备

Removable

A drive that has removable media.

一种移动多媒体设备

Unknown

The drive could not be determined.

无法识别设备

How to Enumerate Drives

如何列举设备

You follow this procedure to access the drives in a system:

你可以沿着这个过程来访问一个系统中的驱动器:

1.    Call the static GetDrives method (or a shared one in Visual Basic) of the DriveInfo class.

2.    Loop through the array of DriveInfo objects returned by GetDrives.

 

调用DriveInfo类的GetDrives静态方法.

GetDrives返回DriveInfo对象数组进行循环.

The following code example illustrates this process:

' VB
Dim drives() As DriveInfo = DriveInfo.GetDrives()
 
Dim drive As DriveInfo
For Each drive In drives
    Console.WriteLine("Drive: {0}", drive.Name)
    Console.WriteLine("Type: {0}", drive.DriveType)
Next
 
// C#
DriveInfo[] drives = DriveInfo.GetDrives();
 
foreach (DriveInfo drive in drives)
{
    Console.WriteLine("Drive: {0}", drive.Name);
    Console.WriteLine("Type: {0}", drive.DriveType);
}

As you can see, the GetDrives method of the DriveInfo object greatly simplifies the process of enumerating the drives in a system.

可以看到,DriveInfo对象的GetDrives方法很容易列举出系统驱动器的步骤.

 

Optical drives 

All types of optical drives (CD, CD/R, DVD, DVD/R, and so on) are marked as DriveInfo.CDRom.

所有的光驱类型(CD, CD/R, DVD, DVD/R)都被标识为DriveInfo.CDRom

The Path Class

The Path class provides methods for manipulating a file system path. Table 2-10 shows the most important Path methods.

Path类提供了操作一个文件系统路径的方法.2-10展示了大部分重要的Path方法

Table 2-10: Static Path Methods

Name

Description

ChangeExtension

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

更改路径字符串,并返回一个改变后的新路径字符串(注意:改变的只是路径字符串,而不是真实的文件扩展名被改变)

Combine

Combines two compatible path strings.

合并两个路径字符串

GetDirectoryName

Returns the name of the directory in the specified path.

返回指定路径的目录名称

GetExtension

Returns the name of the file extension in the specified path.

返回指定路径的文件扩展名

GetFileName

Returns the name of the file in the specified path.

返回指定路径的文件名称

GetFileNameWithoutExtension

Returns the file name without the extension in the specified path.

返回指定路径的文件名称,不包含扩展名

GetFullPath

Returns a full path to the specified path. This method can be used to resolve relative paths.

返回指定路径的绝对路径

GetPathRoot

Returns the root directory name in the specified path.

返回指定路径的根目录名称

GetRandomFileName

Generates a random file name.

产生一个随机文件

GetTempFileName

Generates a temporary file in the file system and returns the full path to the file.

生成一个临时文件并返回这个文件的绝对路径

GetTempPath

Returns the path to the temporary file directory for the current user or system.

返回当前用户或系统临时文件目录路

HasExtension

Indicates whether a specified path's file name has an extension.

显示指定路径下的文件是否有扩展名

IsPathRooted

Indicates whether the specified path includes a root directory.

显示指定路径是否包含一个根目录

How to Change a File Extension

如何改变一个文件的扩展名

The Path class allows you interrogate and parse the individual parts of a file system path. Instead of writing your own string parsing code, the Path class allows you to answer most common questions you would have about a file system path. For example, if you want to get and change the extension of a file, you can do so with the Path class, as shown in the following code snippet:

Path类允许你查询和解析一个文件系统路径部分.Path类允许你查询与你获取的文件系统路径有关的大量常见问题。例如,假设你要获取并改变一个文件的扩展名,你可以象下面示范的代码那样使用Path类。

' VB
Dim ourPath As String = "c:\boot.ini"
Console.WriteLine(ourPath)
 
Console.WriteLine("Ext: {0}", Path.GetExtension(ourPath))
 
Console.WriteLine("Change Path: {0}", _
    Path.ChangeExtension(ourPath, "bak"))
 
// C#
string ourPath = @"c:\boot.ini";
Console.WriteLine(ourPath);
 
Console.WriteLine("Ext: {0}", Path.GetExtension(ourPath));
 
Console.WriteLine("Change Path: {0}",
    Path.ChangeExtension(ourPath, "bak"));

By using the GetExtension method of the Path class, you can get the current extension of a file system path. However, because the original goal was to change the path, you use the ChangeExtension method of the Path class.

利用Path类的GetExtension方法,你能够获取当前文件的扩展名。你可以使用Path类的ChangeExtension方法来改变路径。(注意:改变的只是字符串,而不是真实路径)

The FileSystemWatcher Class

The FileSystemWatcher class provides methods for monitoring file system directories for changes. Table 2-11 shows the most important FileSystemWatcher properties.

FileSystemWatcher类提供了监控系统目录改变的方法。表2-11显示了大部分重要的FileSystemWatcher的属性

Table 2-11: FileSystemWatcher Properties

Name

Description

EnableRaisingEvents

Gets or sets whether the watcher object should raise events. Normally, it's used to turn on and off the watching of a directory and/or files.

设置这个对象是否触发事件。正常情况下,它被用于打开和关闭目录或文件的监视

Filter

Gets or sets the file filter to use to determine which file changes to monitor. A blank filter indicates "all files."

获取和设置文件过滤,用于确定要监控哪些文件的改变。空的过滤代表要监控所有文件

IncludeSubdirectories

Gets or sets an indicator of whether the watching of a directory is to include subdirectories or only the directory specified in the Path property.

获取或设置对一个指定目录的监控,包括它的子目录和文件的更改。

NotifyFilter

Gets or sets the type of changes to watch for. By default, all changes (creation, deletion, renamed files, and modifications) are notified.

获取或设置要监控的变动类型。默认是所有改变都要通知(新建,删除,重命名,修改)

Path

Gets or sets the path to the directory to monitor.

获取或设置监控目录的路径

Table 2-12 shows the most important FileSystemWatcher Method.

Table 2-12: FileSystemWatcher Method

Name

Description

WaitForChanged

Synchronous method for watching a directory for changes and for returning a structure that contains all the changes

同步监控目录的改变,并返回一个结构对象,这个结构对象包含了所有的改变。

Table 2-13 shows the most important FileSystemWatcher events.

Table 2-13: FileSystemWatcher Events

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

被监控目录中的文件或目录被重命名是发生

How to Monitor a Directory for Changes

如何监控一个目录的变更

To monitor a directory for changes, follow this procedure:

如下步骤

1.    Create a new FileSystemWatcher object, specifying the directory in the Path property.

2.    Register for the Created and Deleted events.

3.    Turn on events by setting EnableRaisingEvents to true.

根据Path属性的指定的目录,建立一个新的FileSystemWatcher对象。

注册CreatedDeleted事件。

设置EnableRaisingEventstrue允许事件被触发

The following code snippet demonstrates this process:

下面的代码片断示范这个步骤。

' VB
Dim watcher As FileSystemWatcher = New FileSystemWatcher()
watcher.Path = "c:\"
 
' Register for events
AddHandler watcher.Created, _
    New FileSystemEventHandler(AddressOf watcher_Changed)
AddHandler watcher.Deleted, _
    New FileSystemEventHandler(AddressOf watcher_Changed)
 
' Start Watching
watcher.EnableRaisingEvents = True
 
' Event Handler
Sub watcher_Changed(ByVal sender As Object, _
    ByVal e As FileSystemEventArgs)
 
    Console.WriteLine("Directory changed({0}): {1}", _
        e.ChangeType, _
        e.FullPath)
 
End Sub
 
// C#
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\";
 
// Register for events
watcher.Created +=
    new FileSystemEventHandler(watcher_Changed);
watcher.Deleted +=
    new FileSystemEventHandler(watcher_Changed);
 
// Start Watching
watcher.EnableRaisingEvents = true;
 
// Event Handler
static void watcher_Changed(object sender,
    FileSystemEventArgs e)
 
{
 Console.WriteLine("Directory changed({0}): {1}",
      e.ChangeType,
      e.FullPath);
}

The event handler simply reports each change found in the FileSystemEventArgs object that is sent to the event handler.

事件处理器可以方便的报告在FileSystemEventArgs对象中发现的每个变动。

In addition to using the Added and Changed events, you can monitor the system for renamed files. To monitor a directory for renamed files, you can follow this procedure:

另外,利用AddedChanged事件,你能够监控系统中文件的重命名的发生。如何监控目录中的文件重命名,你可以按照下面过程。

1.    Create a new FileSystemWatcher object, specifying the directory in the Path property.

2.    Register for the Renamed event.

3.    Turn on events by setting EnableRaisingEvents to true.

 

根据Path属性中指定的目录,建立一个新的FileSystemWatcher对象

注册Renamed事件

设置EnableRaisingEventstrue允许事件被触发

The following code snippet demonstrates this process:

下面的代码片断示范这个步骤。

 

' VB
Dim watcher As FileSystemWatcher = New FileSystemWatcher()
watcher.Path = "c:\"
 
' Register for events
AddHandler watcher.Renamed, _
    New RenameEventHandler(AddressOf watcher_Renamed)
 
' Start Watching
watcher.EnableRaisingEvents = True
 
' Event Handler
Sub watcher_Renamed(ByVal sender As Object, _
    ByVal e As RenamedEventArgs)
 
 Console.WriteLine("Renamed from {0} to {1}", _
    e.OldFullPath, _
    e.FullPath)
 
End Sub
 
// C#
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\";
 
// Register for events
watcher.Renamed +=
    new RenamedEventHandler(watcher_Renamed);
 
// Start Watching
watcher.EnableRaisingEvents = true;
 
// Event Handler
static void watcher_Renamed(object sender,
    RenamedEventArgs e)
{
 Console.WriteLine("Renamed from {0} to {1}",
      e.OldFullPath,
      e.FullPath);
}

When watching the file system, you can get more changes than the FileSystemWatcher can handle. When too many events occur, the FileSystemWatcher throws the Error event. To capture the Error event, follow these steps:

当监控文件系统时,你能够获取更多的可以用FileSystemWatcher处理的改变.当太多的事件发生时,FileSystemWatcher将抛出Error事件,要捕获这个Error事件,查看下面这些步骤.

1.    Create a new FileSystemWatcher object, specifying the directory in the Path property.

2.    Register for the Error event.

3.    Turn on events by setting EnableRaisingEvents to true.

 

1.    根据Path属性中指定的目录,建立一个新的FileSystemWatcher对象

2.    注册Error事件

3.    设置EnableRaisingEventstrue允许事件被触发

 

The following code snippet demonstrates this process:

下面的代码片断示范这个步骤。

' VB
Dim watcher As FileSystemWatcher = New FileSystemWatcher()
watcher.Path = "c:\"
 
' Register for events
AddHandler watcher.Error, _
    New ErrorEventHandler(AddressOf watcher_Error)
 
' Start Watching
watcher.EnableRaisingEvents = True
 
' Event Handler
Sub watcher_Error(ByVal sender As Object, _
    ByVal e As ErrorEventArgs)
 
 Console.WriteLine("Error: {0}", _
    e.GetException())
 
End Sub
 
// C#
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\";
 
// Register for events
watcher.Error +=
    new ErrorEventHandler(watcher_Error);
 
// Start Watching
watcher.EnableRaisingEvents = true;
 
// Event Handler
static void watcher_Error(object sender,
    ErrorEventArgs e)
{
 Console.WriteLine("Error: {0}",
    e.GetException());
}

Lab: Enumerate Files and Watch for Changes

实验:列举文件并监控它们的修改

In this lab, you will enumerate through the files of a folder and then watch to see whether any files have changed. If you encounter a problem completing an exercise, the completed projects are available on the companion CD in the Code folder.

在本次实验中,你将列举出一个文件夹中的所有文件,然后,监视它们的变动.

Exercise 1: Enumerating Through the Files in a Folder 练习1:列举文件夹中的所有文件

In this exercise, you will enumerate through all the files in a particular drive.

在本次练习中,你要列举出一个特殊设备中的所有文

1.    Create a new console application named ShowFilesDemo.

2.    建立一个新的控制台应用程序,命名为ShowFilesDemo

3.    Add an Import (or an include in C#) for the System.IO namespace into the new project.

4.    添加System.IO命名空间的引

5.    Add a new method that takes a DirectoryInfo object named ShowDirectory.

6.    添加一个新的方法,它有一个DirectoryInfo对象类型参数,名叫ShowDirectory

7.    Within your new method, iterate through each of the files in your directory and show them in the console one at a time. Your code might look something like this:

8.    在这个新的方法中,循环获取目录中的每个文件,并每次都将它的名字显示在控制台.

9.           ' VB
10.       Sub ShowDirectory(ByVal dir As DirectoryInfo)
11.        
12.           ' Show Each File
13.           Dim file As FileInfo
14.           For Each file In dir.GetFiles()
15.               Console.WriteLine("File: {0}", file.FullName)
16.           Next
17.        
18.       End Sub
19.       // C#
20.       static void ShowDirectory(DirectoryInfo dir)
21.       {
22.           // Show Each File
23.           foreach (FileInfo file in dir.GetFiles())
24.           {
25.               Console.WriteLine("File: {0}", file.FullName);
26.           }
27.       }
28.        

29.Within the ShowDirectory method, iterate through each subdirectory and call the ShowDirectory method. Doing this will call the ShowDirectory recursively to find all the files for every directory. This code might look something like this:

30.ShowDirectory方法中,如果获取的是子目录,就调用ShowDirectory方法本身.利用这种递归ShowDirectory方法来获取每个目录中的文件.

31.       ' VB
32.       ' Go through subdirectories
33.       ' recursively
34.       Dim subDir As DirectoryInfo
35.       For Each subDir In dir.GetDirectories()
36.           ShowDirectory(subDir)
37.       Next
38.        
39.       // C#
40.       // Go through subdirectories
41.       // recursively
42.       foreach (DirectoryInfo subDir in dir.GetDirectories())
43.       {
44.           ShowDirectory(subDir);
45.       }

46.In the Main method, write code to create a new instance of a DirectoryInfo object for the Windows directory and use it to call the new ShowDirectory method. For example, the following code would work:

47.Main方法中编写代码,Windows 目录建立一个新的DirectoryInfo对象的实例.并用它调用ShowDirectory方法.例如下面代码

48.       ' VB
49.       Dim dir As DirectoryInfo = New DirectoryInfo(Environment.SystemDirectory)
50.       ShowDirectory(dir)
51.        
52.       // C#
53.       DirectoryInfo dir = new DirectoryInfo(Environment.SystemDirectory);
54.       ShowDirectory(dir);

55.Build the project and resolve any errors. Verify that the console application successfully lists all the files in the system directory (Environment.SystemDirectory).

56.编译项目并解决错误.验证控制台应用程序成功的列出了系统目录中的所有文件.

 

 

Exercise 2: Watch for Changes in the File System 练习2:监控文件系统的改变

In this exercise, you will watch the file system for changes in all files that end with the .ini extension.

本练习中,你将监控文件系统中所有文件扩展名为ini的文件的改,

1.    Create a new console application named FileWatchingDemo.

2.    建立一个名为FileWatchingDemo的控制台应用程序

3.    Import the System.IO namespace into the new file.

4.    引用System.IO命名空间

5.    Create a new instance of the FileSystemWatcher class, specifying the system directory. For example, you could use the following code:

6.    建立一个指定系统目录的FileSystemWatcher类的实例.

7.           ' VB
8.           Dim watcher As New FileSystemWatcher(Environment.SystemDirectory)
9.            
10.       // C#
11.       FileSystemWatcher watcher =
12.           new FileSystemWatcher(Environment.SystemDirectory);
13.        

14.Modify properties of the file system watcher to look only for .ini files, search through all subdirectories, and accept changes only if the attributes of the file change or if the file size changes. Your code might look like this:

15.修改监控的文件属性为扩展名为.ini的文件.搜索所有子目录,并只监控文件属性的改变或文件大小的改变.

16.       ' VB
17.       watcher.Filter = "*.ini"
18.       watcher.IncludeSubdirectories = True
19.       watcher.NotifyFilter = _
20.           NotifyFilters.Attributes Or NotifyFilters.Size
21.        
22.       // C#
23.       watcher.Filter = "*.ini";
24.       watcher.IncludeSubdirectories = true;
25.       watcher.NotifyFilter =
26.         NotifyFilters.Attributes | NotifyFilters.Size;

27.To see the changes, add a handler for the Changed event of your watcher object. For example, you could use the following code:

28.为你的监控对象的Changed事件加一个处理过程.

29.       ' VB
30.       AddHandler watcher.Changed, _
31.           New FileSystemEventHandler(AddressOf watcher_Changed)
32.        
33.       // C#
34.       watcher.Changed +=
35.           new FileSystemEventHandler(watcher_Changed);

36.Next you need the method that the Changed event is going to call. Inside this method, write out to the console the name of the changed file. Your code might look something like this:

37.下面,你需要编写这个Changed事件要调用的方法.在这个方法中,向控制台输出被改变文件的名称.

38.       ' VB
39.       Sub watcher_Changed(ByVal sender As Object, _
40.                           ByVal e As FileSystemEventArgs)
41.        
42.           Console.WriteLine("Changed: {0}", e.FullPath)
43.        
44.       End Sub
45.        
46.       // C#
47.       static void watcher_Changed(object sender,
48.           FileSystemEventArgs e)
49.       {
50.           Console.WriteLine("Changed: {0}", e.FullPath);
51.       }

52.Set the EnablingRaisingEvents property to true to tell the watcher object to start throwing events.

53.设置EnableingRaisingEvents属性为true.来允许监控对象抛出事

54.Build the project and resolve any errors. Verify that the console application successfully reports when the attributes of any .ini file change or when the file size changes.

55.编译这个项目,并解决所有问题.验证控制台应用程序顺利的报告了ini文件属性的改变或文件大小的改变.

 

 

Lesson Summary本课摘要

·         The FileInfo, DirectoryInfo, and DriveInfo classes can be used to enumerate and inspect the properties of file system objects.

·         The Path class can be used to interrogate a file system path and should be used instead of parsing the string manually.

·         The FileSystemWatcher class can be used to monitor the file system for changes such as additions, deletions, and renamings.

·         FileInfo,DirectoryInfo,DriveInfo类能够被用于列举并检查文件系统对象的属性

·         Path类能够被用于查询一个文件系统路径,并手动替换解析的字符串

·         FileSystemWatcher类能够用于监控文件系统的改变,例如增加,删除,和重命名.

Lesson Review课后复习

You can use the following questions to test your knowledge of the information in Lesson 1, "Navigating the File System." The questions are also available on the companion CD if you prefer to review them in electronic form.

下面问题可以测试你在本课中学到的知识.

 

Answers 

Answers to these questions and explanations of why each answer choice is right or wrong are located in the "Answers" section at the end of the book.

回答这些问题并解释每个答案为什么正确或错误.

 

1. 

Which are acceptable ways to open a file for writing? (Choose all that apply.)

下面哪几种方式打开的文件可以写入?

A.           ' VB
B.           File.Open("somefile.txt", FileMode.Create)
C.            
D.           // C#
E.           File.Open("somefile.txt", FileMode.Create);
  1.  
G.           ' VB
H.           File.Open("somefile.txt", FileMode.Create, FileAccess.Write)
I.            
J.           // C#
K.           File.Open("somefile.txt", FileMode.Create, FileAccess.Write);
  1.  
M.           ' VB
N.           File.Open("somefile.txt", FileMode.Create, FileAccess.Read)
O.            
P.           // C#
Q.           File.Open("somefile.txt", FileMode.Create, FileAccess.Read);
R.            
  1.  
T.           ' VB
U.           Dim file As new FileInfo("somefile.txt")
V.           file.Open(FileMode.Create)
W.            
X.           // C#
Y.           FileInfo file = new FileInfo("somefile.txt");
Z.           file.Open(FileMode.Create);
  1.  

2. 

Which of the following are types of changes that can be detected by the FileSystemWatcher? (Choose all that apply.)

下面哪些类型的改变将被FileSystemWatcher监控到?

A.    New files

B.    New directories

C.    Changed files

D.    Renamed files

E.    None

3. 

The following code changes the extension of a file. (True or False)

下面代码能够改变文件的扩展名吗?true or false

' VB
Dim ourPath As String = "c:\boot.ini"
Path.ChangeExtension(ourPath, "bak")
 
// C#
string ourPath = @"c:\boot.ini";
Path.ChangeExtension(ourPath, "bak");

A.    True

B.    False

Answers

1. 

Correct Answers: A, B, and D

A.    Correct: Not specifying the FileAccess on File.Open defaults to read/write access.

没有指定FileAccess,默认是可读写的

B.    Correct: Explicitly using the FileAccess.Write value allows you to write to the file.

指定为可写的

C.    Incorrect: Explicitly using the FileAccess.Read prohibits writing to the file.

指定为只读的,当然不可写

D.    Correct: Creating a new FileInfo object and opening it with FileMode.Create defaults to read/write access to the file.

新建一个FileInfo对象并用FileMode.Create打开,默认是可读写的

2. 

Correct Answers: A, B, C, and D 可以报告新文件,新目录,文件改变,文件重命名

A.    Correct: The FileSystemWatcher can report on new files.

B.    Correct: The FileSystemWatcher can report on new directories.

C.    Correct: The FileSystemWatcher can report on file changes.

D.    Correct: The FileSystemWatcher can report on renamed files.

E.    Incorrect: All of these changes can be detected.

3. 

Correct Answer: B 只是改变了路径字符串,而没有真正改变系统文件路径

A.    Incorrect: The Path class deals only with the string of a path. It makes no changes to the file system.

B.    Correct: The Path class deals only with the string of a path. It makes no changes to the file system.

 

你可能感兴趣的:(application)