文件和流 I/OFile and Stream I/O

文件和流 I/O(输入/输出)是指在存储媒介中传入或传出数据。File and stream I/O (input/output) refers to the transfer of data either to or from a storage medium. 在 .NET Framework 中,System.IO 命名空间包含允许以异步方式和同步方式对数据流和文件进行读取和写入操作的类型。In the .NET Framework, the System.IO namespaces contain types that enable reading and writing, both synchronously and asynchronously, on data streams and files. 这些命名空间还包含对文件执行压缩和解压缩的类型,以及通过管道和串行端口启用通信的类型。These namespaces also contain types that perform compression and decompression on files, and types that enable communication through pipes and serial ports.

文件是一个由字节组成的有序的命名集合,它具有永久存储。A file is an ordered and named collection of bytes that has persistent storage. 在处理文件时,你将处理目录路径、磁盘存储、文件和目录名称。When you work with files, you work with directory paths, disk storage, and file and directory names. 相反,流是一个字节序列,可用于对后备存储进行读取和写入操作,后备存储可以是多个存储媒介之一(例如,磁盘或内存)。In contrast, a stream is a sequence of bytes that you can use to read from and write to a backing store, which can be one of several storage mediums (for example, disks or memory). 正如存在除磁盘之外的多种后备存储一样,也存在除文件流之外的多种流(如网络、内存和管道流)。Just as there are several backing stores other than disks, there are several kinds of streams other than file streams, such as network, memory, and pipe streams.

文件和目录Files and directories

你可以使用 System.IO 命名空间中的类型与文件和目录进行交互。You can use the types in the System.IO namespace to interact with files and directories. 例如,你可以获取和设置文件和目录的属性,并基于搜索条件检索文件和目录的集合。For example, you can get and set properties for files and directories, and retrieve collections of files and directories based on search criteria.

若要深入了解 Windows 系统中的路径命名约定和 文件路径的表示方式,包括在 .NET Core 1.1 及更高版本和 .NET Framework 4.6.2 及更高版本中支持的 DOS 设备语法,请参阅 Windows 系统中的文件路径格式For path naming conventions and the ways to express a file path for Windows systems, including with the DOS device syntax supported in .NET Core 1.1 and later and the .NET Framework 4.6.2 and later, see File path formats on Windows systems.

下面是一些常用的文件和目录类:Here are some commonly used file and directory classes:

  • File - 提供用于创建、复制、删除、移动和打开文件的静态方法,并可帮助创建 FileStream 对象。File - provides static methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object.

  • FileInfo - 提供用于创建、复制、删除、移动和打开文件的实例方法,并可帮助创建 FileStream 对象。FileInfo - provides instance methods for creating, copying, deleting, moving, and opening files, and helps create a FileStream object.

  • Directory - 提供用于创建、移动和枚举目录和子目录的静态方法。Directory - provides static methods for creating, moving, and enumerating through directories and subdirectories.

  • DirectoryInfo - 提供用于创建、移动和枚举目录和子目录的实例方法。DirectoryInfo - provides instance methods for creating, moving, and enumerating through directories and subdirectories.

  • Path - 提供用于以跨平台的方式处理目录字符串的方法和属性。Path - provides methods and properties for processing directory strings in a cross-platform manner.

调用文件系统方法时,应始终提供强大的异常处理。You should always provide robust exception handling when calling filesystem methods. 有关更多信息,请参阅处理 I/O 错误异常For more information, see Handling I/O errors.

除了使用这些类之外,Visual Basic 用户还可以对文件 I/O 使用 Microsoft.VisualBasic.FileIO.FileSystem 类提供的方法和属性。In addition to using these classes, Visual Basic users can use the methods and properties provided by the Microsoft.VisualBasic.FileIO.FileSystem class for file I/O.

请参阅如何:复制目录如何:创建目录列表如何:枚举目录和文件See How to: Copy Directories, How to: Create a Directory Listing, and How to: Enumerate Directories and Files.


抽象基类 Stream 支持读取和写入字节。The abstract base class Stream supports reading and writing bytes. 所有表示流的类都继承自 Stream 类。All classes that represent streams inherit from the Stream class. Stream 类及其派生类提供数据源和存储库的常见视图,使程序员不必了解操作系统和基础设备的具体细节。The Stream class and its derived classes provide a common view of data sources and repositories, and isolate the programmer from the specific details of the operating system and underlying devices.

流涉及三个基本操作:Streams involve three fundamental operations:

  • 读取 - 将数据从流传输到数据结构(如字节数组)中。Reading - transferring data from a stream into a data structure, such as an array of bytes.

  • 写入 - 将数据从数据源传输到流。Writing - transferring data to a stream from a data source.

  • 查找 - 对流中的当前位置进行查询和修改。Seeking - querying and modifying the current position within a stream.

根据基础数据源或存储库,流可能只支持这些功能中的一部分。Depending on the underlying data source or repository, a stream might support only some of these capabilities. 例如,PipeStream 类不支持查找。For example, the PipeStream class does not support seeking. 流的 CanReadCanWriteCanSeek 属性指定流支持的操作。The CanRead, CanWrite, and CanSeek properties of a stream specify the operations that the stream supports.

下面是一些常用的流类:Here are some commonly used stream classes:

  • FileStream - 用于对文件进行读取和写入操作。FileStream – for reading and writing to a file.

  • IsolatedStorageFileStream - 用于对独立存储中的文件进行读取或写入操作。IsolatedStorageFileStream – for reading and writing to a file in isolated storage.

  • MemoryStream - 用于作为后备存储对内存进行读取和写入操作。MemoryStream – for reading and writing to memory as the backing store.

  • BufferedStream - 用于改进读取和写入操作的性能。BufferedStream – for improving performance of read and write operations.

  • NetworkStream - 用于通过网络套接字进行读取和写入。NetworkStream – for reading and writing over network sockets.

  • PipeStream - 用于通过匿名和命名管道进行读取和写入。PipeStream – for reading and writing over anonymous and named pipes.

  • CryptoStream - 用于将数据流链接到加密转换。CryptoStream – for linking data streams to cryptographic transformations.

有关异步使用流的示例,请参阅异步文件 I/OFor an example of working with streams asynchronously, see Asynchronous File I/O.

读取器和编写器Readers and writers

System.IO 命名空间还提供用于在流中读取和写入已编码字符的类型。The System.IO namespace also provides types for reading encoded characters from streams and writing them to streams. 通常,流用于字节输入和输出。Typically, streams are designed for byte input and output. 读取器和编写器类型处理编码字符与字节之间的来回转换,以便流可以完成操作。The reader and writer types handle the conversion of the encoded characters to and from bytes so the stream can complete the operation. 每个读取器和编写器类都与流关联,可以通过类的 BaseStream 属性进行检索。Each reader and writer class is associated with a stream, which can be retrieved through the class's BaseStream property.

下面是一些常用的读取器和编写器类:Here are some commonly used reader and writer classes:

  • BinaryReaderBinaryWriter - 用于将基元数据类型作为二进制值进行读取和写入。BinaryReader and BinaryWriter – for reading and writing primitive data types as binary values.

  • StreamReaderStreamWriter - 用于通过使用编码值在字符和字节之间来回转换来读取和写入字符。StreamReader and StreamWriter – for reading and writing characters by using an encoding value to convert the characters to and from bytes.

  • StringReaderStringWriter - 用于从字符串读取字符以及将字符写入字符串中。StringReader and StringWriter – for reading and writing characters to and from strings.

  • TextReaderTextWriter - 用作其他读取器和编写器(读取和写入字符和字符串,而不是二进制数据)的抽象基类。TextReader and TextWriter – serve as the abstract base classes for other readers and writers that read and write characters and strings, but not binary data.

请参阅如何:从文件读取文本如何:向文件写入文本如何:从字符串中读取字符如何:向字符串写入字符See How to: Read Text from a File, How to: Write Text to a File, How to: Read Characters from a String, and How to: Write Characters to a String.

异步 I/O 操作Asynchronous I/O operations

读取或写入大量数据会占用大量资源。Reading or writing a large amount of data can be resource-intensive. 如果你的应用程序需要保持对用户的响应性,则你应异步执行这些任务。You should perform these tasks asynchronously if your application needs to remain responsive to the user. 在执行同步 I/O 操作时,UI 线程将受阻,直至完成占用大量资源的操作。With synchronous I/O operations, the UI thread is blocked until the resource-intensive operation has completed. 在开发 Windows 8.x 应用商店Windows 8.x Store应用时使用异步 I/O 操作可防止造成应用程序已停止工作的印象。Use asynchronous I/O operations when developing Windows 8.x 应用商店Windows 8.x Store apps to prevent creating the impression that your app has stopped working.

异步成员在其名称中包含 Async,如 CopyToAsyncFlushAsyncReadAsyncWriteAsync 方法。The asynchronous members contain Async in their names, such as the CopyToAsync, FlushAsync, ReadAsync, and WriteAsync methods. 你可以将这些方法与 asyncawait 关键字一起使用。You use these methods with the async and await keywords.

有关详细信息,请参阅异步文件 I/OFor more information, see Asynchronous File I/O.


压缩是指减小文件大小以便存储的过程。Compression refers to the process of reducing the size of a file for storage. 解压缩是提取压缩文件的内容以使这些内容采用可用格式的过程。Decompression is the process of extracting the contents of a compressed file so they are in a usable format. System.IO.Compression 命名空间包含用于对文件和流进行压缩或解压缩的类型。The System.IO.Compression namespace contains types for compressing and decompressing files and streams.

在对文件和流进行压缩和解压缩时,经常使用以下类:The following classes are frequently used when compressing and decompressing files and streams:

  • ZipArchive - 用于在 zip 存档中创建和检索条目。ZipArchive – for creating and retrieving entries in the zip archive.

  • ZipArchiveEntry - 用于表示压缩文件。ZipArchiveEntry – for representing a compressed file.

  • ZipFile - 用于创建、提取和打开压缩包。ZipFile – for creating, extracting, and opening a compressed package.

  • ZipFileExtensions - 用于创建和提供压缩包中的条目。ZipFileExtensions – for creating and extracting entries in a compressed package.

  • DeflateStream - 用于使用 Deflate 算法对流进行压缩和解压缩。DeflateStream – for compressing and decompressing streams using the Deflate algorithm.

  • GZipStream - 用于采用 gzip 数据格式对流进行压缩和解压缩。GZipStream – for compressing and decompressing streams in gzip data format.

请参阅如何:压缩和解压缩文件See How to: Compress and Extract Files.

独立存储Isolated storage

独立存储是一种数据存储机制,它在代码与保存的数据之间定义了标准化的关联方式,从而提供隔离性和安全性。Isolated storage is a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data. 存储提供按用户、程序集和(可选)域隔离的虚拟文件系统。The storage provides a virtual file system that is isolated by user, assembly, and (optionally) domain. 当你的应用程序无权访问用户文件时,独立存储特别有用。Isolated storage is particularly useful when your application does not have permission to access user files. 你可以通过一种由计算机的安全策略控制的方式保存应用程序的设置或文件。You can save settings or files for your application in a manner that is controlled by the computer's security policy.

独立存储不可用于 Windows 8.x 应用商店Windows 8.x Store 应用;请改用 Windows.Storage 命名空间中的应用程序数据类。Isolated storage is not available for Windows 8.x 应用商店Windows 8.x Store apps; instead, use application data classes in the Windows.Storage namespace. 有关详细信息,请参阅应用程序数据For more information, see Application data.

在实现独立存储时,经常使用以下类:The following classes are frequently used when implementing isolated storage:

请参阅独立存储See Isolated Storage.

Windows 应用商店应用程序中的 I/O 操作I/O operations in Windows Store apps

适用于 Windows 8.x 应用商店应用的 .NET.NET for Windows 8.x Store apps 包含许多用于对流进行读取和写入操作的类型;但是,该集不包含所有的 .NET Framework I/O 类型。The 适用于 Windows 8.x 应用商店应用的 .NET.NET for Windows 8.x Store apps contains many of the types for reading from and writing to streams; however, this set does not include all the .NET Framework I/O types.

Windows 8.x 应用商店Windows 8.x Store应用中使用 I/O 操作时,要注意一些重要差异:Some important differences to note when using I/O operations in Windows 8.x 应用商店Windows 8.x Store apps:

如果需要,你可以在 .NET Framework 流和 Windows 运行时流之间进行转换。You can convert between .NET Framework streams and Windows Runtime streams, if necessary. 有关详细信息,请参阅如何:在 .NET Framework 流和 Windows 运行时流之间进行转换WindowsRuntimeStreamExtensionsFor more information, see How to: Convert Between .NET Framework Streams and Windows Runtime Streams or WindowsRuntimeStreamExtensions.

若要深入了解 Windows 8.x 应用商店Windows 8.x Store 应用中的 I/O 操作,请参阅快速入门:读取和写入文件For more information about I/O operations in a Windows 8.x 应用商店Windows 8.x Store app, see Quickstart: Reading and writing files.

I/O 和安全性I/O and security

在使用 System.IO 命名空间中的类时,你必须遵循操作系统安全性要求(如访问控制列表 (ACL))来控制对文件和目录的访问。When you use the classes in the System.IO namespace, you must follow operating system security requirements such as access control lists (ACLs) to control access to files and directories. 此要求是在所有 FileIOPermission 要求之外的要求。This requirement is in addition to any FileIOPermission requirements. 可以用编程方式管理 ACL。You can manage ACLs programmatically. 有关详细信息,请参阅如何:添加或删除访问控制列表条目For more information, see How to: Add or Remove Access Control List Entries.

默认安全策略将阻止 Internet 或 Intranet 应用程序访问用户计算机上的文件。Default security policies prevent Internet or intranet applications from accessing files on the user’s computer. 因此,在编写将通过 Internet 或 Intranet 下载的代码时,请不要使用需要物理文件路径的 I/O 类。Therefore, do not use the I/O classes that require a path to a physical file when writing code that will be downloaded over the Internet or intranet. 请转而将独立存储用于传统 .NET Framework 应用程序,或将应用程序数据用于 Windows 8.x 应用商店Windows 8.x Store 应用。Instead, use isolated storage for traditional .NET Framework applications, or use application data for Windows 8.x 应用商店Windows 8.x Store apps.

仅在构造流时执行安全性检查。A security check is performed only when the stream is constructed. 因此,请不要打开流并将其传递给受信程度较低的代码或应用程序域。Therefore, do not open a stream and then pass it to less-trusted code or application domains.

  • 通用 I/O 任务Common I/O Tasks
    提供与文件、目录和流关联的 I/O 任务的列表以及指向每个任务的相关内容和示例的链接。Provides a list of I/O tasks associated with files, directories, and streams, and links to relevant content and examples for each task.

  • 异步文件 I/OAsynchronous File I/O
    描述异步 I/O 的性能优势和基本操作。Describes the performance advantages and basic operation of asynchronous I/O.

  • 独立存储Isolated Storage
    描述一种数据存储机制,该机制通过定义标准的代码与保存数据的关联方式来提供隔离和安全性。Describes a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data.

  • 管道Pipes
    描述 .NET Framework 中的匿名和命名管道操作。Describes anonymous and named pipe operations in the .NET Framework.

  • 内存映射文件Memory-Mapped Files
    描述内存映射文件,这些文件包含虚拟内存中磁盘上文件的内容。Describes memory-mapped files, which contain the contents of files on disk in virtual memory. 可以使用内存映射文件编辑非常大的文件和创建共享内存以进行进程间通信。You can use memory-mapped files to edit very large files and to create shared memory for interprocess communication.