Stream 類別

定義

提供位元組順序的一般觀點。Provides a generic view of a sequence of bytes. 這是 abstract 類別。This is an abstract class.

public ref class Stream abstract : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class Stream : MarshalByRefObject, IDisposable
type Stream = class
    inherit MarshalByRefObject
    interface IDisposable
Public MustInherit Class Stream
Inherits MarshalByRefObject
Implements IDisposable
繼承
衍生
屬性
實作

範例

下列範例示範如何使用兩個FileStream物件,以非同步方式將檔案從一個目錄複寫到另一個目錄。The following example demonstrates how to use two FileStream objects to asynchronously copy the files from one directory to another directory. FileStream 類別衍生自 Stream 類別。The FileStream class derives from the Stream class. 請注意, Click 控制項的 Button 事件處理常式由於會呼叫非同步方法,因此會以 async 修飾詞標記。Notice that the Click event handler for the Button control is marked with the async modifier because it calls an asynchronous method.

using System;
using System.Threading.Tasks;
using System.Windows;
using System.IO;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string StartDirectory = @"c:\Users\exampleuser\start";
            string EndDirectory = @"c:\Users\exampleuser\end";

            foreach (string filename in Directory.EnumerateFiles(StartDirectory))
            {
                using (FileStream SourceStream = File.Open(filename, FileMode.Open))
                {
                    using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                    {
                        await SourceStream.CopyToAsync(DestinationStream);
                    }
                }
            }
        }
    }
}
Imports System.IO

Class MainWindow

    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim StartDirectory As String = "c:\Users\exampleuser\start"
        Dim EndDirectory As String = "c:\Users\exampleuser\end"

        For Each filename As String In Directory.EnumerateFiles(StartDirectory)
            Using SourceStream As FileStream = File.Open(filename, FileMode.Open)
                Using DestinationStream As FileStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf("\"c)))
                    Await SourceStream.CopyToAsync(DestinationStream)
                End Using

            End Using
        Next
    End Sub

End Class

備註

Stream是所有資料流程的抽象基類。Stream is the abstract base class of all streams. 資料流是位元組序列的抽象,例如,檔案、輸入/輸出裝置、處理序間的通訊管道或 TCP/IP 通訊端。A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. Stream類別及其衍生類別提供這些不同類型之輸入和輸出的一般觀點,並且將程式設計人員與作業系統和基礎裝置的特定詳細資料隔離。The Stream class and its derived classes provide a generic view of these different types of input and output, and isolate the programmer from the specific details of the operating system and the underlying devices.

資料流包含三項基本作業:Streams involve three fundamental operations:

  • 您可以從資料流程讀取。You can read from streams. 讀取是指將資料流程中的資料傳輸至資料結構,例如位元組陣列。Reading is the transfer of data from a stream into a data structure, such as an array of bytes.

  • 您可以寫入資料流程。You can write to streams. 寫入是指從資料結構傳送資料到資料流程。Writing is the transfer of data from a data structure into a stream.

  • 資料流程可以支援搜尋。Streams can support seeking. 搜尋是指查詢和修改資料流程中的目前位置。Seeking refers to querying and modifying the current position within a stream. 搜尋功能取決於資料流程具有的備份存放區類型。Seek capability depends on the kind of backing store a stream has. 例如,網路資料流程沒有目前位置的統一概念,因此通常不支援搜尋。For example, network streams have no unified concept of a current position, and therefore typically do not support seeking.

繼承自Stream的一些較常使用的資料流程是FileStream、和MemoryStreamSome of the more commonly used streams that inherit from Stream are FileStream, and MemoryStream.

根據基礎資料來源或存放庫,資料流程可能只支援其中部分功能。Depending on the underlying data source or repository, streams might support only some of these capabilities. 您可以使用CanRead Stream類別的、和CanSeek屬性, CanWrite查詢資料流程的功能。You can query a stream for its capabilities by using the CanRead, CanWrite, and CanSeek properties of the Stream class.

ReadWrite方法會以各種格式讀取和寫入資料。The Read and Write methods read and write data in a variety of formats. 對於支援搜尋的資料流程,請使用SeekSetLength方法,以及PositionLength屬性來查詢和修改資料流程的目前位置和長度。For streams that support seeking, use the Seek and SetLength methods and the Position and Length properties to query and modify the current position and length of a stream.

此型別代表 IDisposable 介面。This type implements the IDisposable interface. 當您完成使用型別時,您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接處置型別,請呼叫其 try/catch 區塊中的 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要間接處置它,請使用語言建構函式,例如 using (在 C# 中) 或 Using (在 Visual Basic 中)。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 如需詳細資訊,請參閱 IDisposable 介面文章中的<使用實作 IDisposable 的物件>一節。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

處置物件會排清任何緩衝的資料,基本上會Flush為您呼叫方法。 StreamDisposing a Stream object flushes any buffered data, and essentially calls the Flush method for you. Dispose也會釋放作業系統資源,例如用於任何內部緩衝的檔案控制代碼、網路連接或記憶體。Dispose also releases operating system resources such as file handles, network connections, or memory used for any internal buffering. BufferedStream類別提供包裝另一個資料流程的緩衝資料流程,以改善讀取和寫入效能的功能。The BufferedStream class provides the capability of wrapping a buffered stream around another stream in order to improve read and write performance.

.NET Framework 4.5.NET Framework 4.5從開始Stream ,類別包含非同步方法,可簡化非同步作業。Starting with the .NET Framework 4.5.NET Framework 4.5, the Stream class includes async methods to simplify asynchronous operations. 非同步方法會在Async其名稱中包含, ReadAsync例如、 WriteAsyncCopyToAsyncFlushAsyncAn async method contains Async in its name, such as ReadAsync, WriteAsync, CopyToAsync, and FlushAsync. 這些方法可讓您執行耗用大量資源的 i/o 作業,而不會封鎖主執行緒。These methods enable you to perform resource-intensive I/O operations without blocking the main thread. 這項效能考量對於 Windows 8.x 市集Windows 8.x Store 應用程式或 桌面desktop 應用程式而言特別重要,尤其是針對耗時的資料流作業可能會阻礙 UI 執行緒,使應用程式看起來像是停止運作的情況。This performance consideration is particularly important in a Windows 8.x 市集Windows 8.x Store app or 桌面desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. 非同步方法會與 Visual Basic 和async C#中的和await關鍵字搭配使用。The async methods are used in conjunction with the async and await keywords in Visual Basic and C#.

Windows 8.x 市集Windows 8.x Store應用程式中使用時Stream ,包括兩個擴充AsInputStream方法AsOutputStream:和。When used in a Windows 8.x 市集Windows 8.x Store app, Stream includes two extension methods: AsInputStream and AsOutputStream. 這些方法會將Stream物件轉換成Windows 執行階段Windows Runtime中的資料流程。These methods convert a Stream object to a stream in the Windows 執行階段Windows Runtime. Windows 執行階段Windows Runtime您也可以使用Stream AsStreamForRead和方法,將中的資料流程轉換成物件。AsStreamForWriteYou can also convert a stream in the Windows 執行階段Windows Runtime to a Stream object by using the AsStreamForRead and AsStreamForWrite methods. 如需詳細資訊,請參閱如何:在 .NET Framework 資料流與 Windows 執行階段資料流之間轉換For more information, see How to: Convert Between .NET Framework Streams and Windows Runtime Streams

某些串流處理會執行基礎資料的本機緩衝,以改善效能。Some stream implementations perform local buffering of the underlying data to improve performance. 針對這類資料流程,您可以使用FlushFlushAsync方法來清除任何內部緩衝區,並確保所有資料都已寫入基礎資料來源或儲存機制。For such streams, you can use the Flush or FlushAsync method to clear any internal buffers and ensure that all data has been written to the underlying data source or repository.

如果您需要不含備份存放區的資料流程(也稱為「位 bucket」),請Null使用欄位來抓取專為此用途而設計的資料流程實例。If you need a stream with no backing store (also known as a bit bucket), use the Null field to retrieve an instance of a stream that is designed for this purpose.

給實施者的注意事項

當您執行的衍生類別Stream時,您必須提供Read(Byte[], Int32, Int32)Write(Byte[], Int32, Int32)方法的實作為。When you implement a derived class of Stream, you must provide implementations for the Read(Byte[], Int32, Int32) and Write(Byte[], Int32, Int32) methods. ReadAsync(Byte[], Int32, Int32)非同步方法Write(Byte[], Int32, Int32)WriteAsync(Byte[], Int32, Int32)CopyToAsync(Stream)會在其執行中使用Read(Byte[], Int32, Int32)同步方法和。The asynchronous methods ReadAsync(Byte[], Int32, Int32), WriteAsync(Byte[], Int32, Int32), and CopyToAsync(Stream) use the synchronous methods Read(Byte[], Int32, Int32) and Write(Byte[], Int32, Int32) in their implementations. 因此, Read(Byte[], Int32, Int32)Write(Byte[], Int32, Int32)的執行會與非同步方法正確搭配運作。Therefore, your implementations of Read(Byte[], Int32, Int32) and Write(Byte[], Int32, Int32) will work correctly with the asynchronous methods. 的預設執行ReadByte() ,並WriteByte(Byte)建立新的單一元素位元組陣列,然後呼叫和Write(Byte[], Int32, Int32)Read(Byte[], Int32, Int32)實值。The default implementations of ReadByte() and WriteByte(Byte) create a new single-element byte array, and then call your implementations of Read(Byte[], Int32, Int32) and Write(Byte[], Int32, Int32). 當您衍生自Stream時,我們建議您覆寫這些方法來存取您的內部緩衝區(如果有的話),以大幅提升效能。When you derive from Stream, we recommend that you override these methods to access your internal buffer, if you have one, for substantially better performance. 您也必須CanRead提供、 Flush() 、、、LengthPosition、和的SetLength(Int64)執行。 Seek(Int64, SeekOrigin) CanWrite CanSeekYou must also provide implementations of CanRead, CanSeek, CanWrite, Flush(), Length, Position, Seek(Int64, SeekOrigin), and SetLength(Int64).

請不要覆寫Close()方法,而是將Stream所有清除邏輯放在Dispose(Boolean)方法中。Do not override the Close() method, instead, put all the Stream cleanup logic in the Dispose(Boolean) method. 如需詳細資訊,請參閱執行 Dispose 方法For more information, see Implementing a Dispose Method.

建構函式

Stream()

初始化 Stream 類別的新執行個體。Initializes a new instance of the Stream class.

欄位

Null

沒有底層存放區的 StreamA Stream with no backing store.

屬性

CanRead

在衍生類別中覆寫時,取得指示目前的資料流是否支援讀取的數值。When overridden in a derived class, gets a value indicating whether the current stream supports reading.

CanSeek

在衍生類別中覆寫時,取得指示目前資料流是否支援搜尋的數值。When overridden in a derived class, gets a value indicating whether the current stream supports seeking.

CanTimeout

取得值,該值判斷目前的資料流是否可以逾時。Gets a value that determines whether the current stream can time out.

CanWrite

在衍生類別中覆寫時,取得指示目前資料流是否支援寫入的數值。When overridden in a derived class, gets a value indicating whether the current stream supports writing.

Length

在衍生類別中覆寫時,取得資料流的長度 (以位元組為單位)。When overridden in a derived class, gets the length in bytes of the stream.

Position

在衍生類別中覆寫時,取得或設定在目前資料流的位置。When overridden in a derived class, gets or sets the position within the current stream.

ReadTimeout

取得或設定值 (以毫秒為單位),這個值決定在逾時前資料流將嘗試讀取多長時間。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.

WriteTimeout

取得或設定值 (以毫秒為單位),這個值決定在逾時前資料流將嘗試寫入多長時間。Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.

方法

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的讀取作業。Begins an asynchronous read operation. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步的寫入作業。Begins an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. 請確定正確地處置資料流,而非呼叫這個方法。Instead of calling this method, ensure that the stream is properly disposed.

CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream.

CopyTo(Stream, Int32)

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

CopyToAsync(Stream, CancellationToken)

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

Dispose(Boolean)

釋放 Stream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

DisposeAsync()

以非同步方式釋放 Stream 使用的不受控資源。Asynchronously releases the unmanaged resources used by the Stream.

EndRead(IAsyncResult)

等候暫止的非同步讀取完成。Waits for the pending asynchronous read to complete. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

EndWrite(IAsyncResult)

結束非同步的寫入作業。Ends an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Flush()

當在衍生類別中覆寫時,會清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

FlushAsync(CancellationToken)

以非同步的方式清除這個資料流的所有緩衝區,造成所有緩衝資料都寫入基礎裝置,並且監視取消要求。Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ObjectInvariant()

提供 Contract 的支援。Provides support for a Contract.

Read(Byte[], Int32, Int32)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Read(Span<Byte>)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

ReadAsync(Byte[], Int32, Int32)

以非同步的方式從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

Seek(Int64, SeekOrigin)

在衍生類別中覆寫時,設定在目前資料流的位置。When overridden in a derived class, sets the position within the current stream.

SetLength(Int64)

在衍生類別中覆寫時,設定目前資料流的長度。When overridden in a derived class, sets the length of the current stream.

Synchronized(Stream)

在指定的 Stream 物件周圍建立安全執行緒 (同步處理) 的包裝函式。Creates a thread-safe (synchronized) wrapper around the specified Stream object.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Write(Byte[], Int32, Int32)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

WriteAsync(Byte[], Int32, Int32)

以非同步的方式將位元組序列寫入至目前的資料流,並依寫入的位元組數將資料流中目前的位置往前移。Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。Writes a byte to the current position in the stream and advances the position within the stream by one byte.

明確介面實作

IDisposable.Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

擴充方法

AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸入資料流。Converts a managed stream in the .NET for Windows Store apps to an input stream in the Windows Runtime.

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的受控資料流轉換成 Windows 執行階段中的輸出資料流。Converts a managed stream in the .NET for Windows Store apps to an output stream in the Windows Runtime.

AsRandomAccessStream(Stream)

將指定的資料流轉換為隨機存取資料流。Converts the specified stream to a random access stream.

適用於

另請參閱