檔案和資料流 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 使用者還可以使用 Microsoft.VisualBasic.FileIO.FileSystem 類別針對檔案 I/O 提供的方法。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.

資料流Streams

抽象基底類別 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

壓縮是指縮減檔案大小以便儲存的程序。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

隔離儲存區 (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.

隔離儲存區 (Isolated Storage) 不適用於 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 執行階段資料流之間WindowsRuntimeStreamExtensions 之間轉換。For 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.

預設安全性原則可避免網際網路或內部網路應用程式存取使用者電腦上的檔案。Default security policies prevent Internet or intranet applications from accessing files on the user’s computer. 因此,撰寫將透過網際網路或內部網路下載的程式碼時,請不要使用需要實體檔案路徑的 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.