FileStream FileStream FileStream FileStream Class

定義

為檔案提供 Stream,同時支援同步與非同步讀取和寫入作業。Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

public ref class FileStream : System::IO::Stream
[System.Runtime.InteropServices.ComVisible(true)]
public class FileStream : System.IO.Stream
type FileStream = class
    inherit Stream
Public Class FileStream
Inherits Stream
繼承
屬性

範例

下列範例示範一些FileStream函數。The following example demonstrates some of the FileStream constructors.

using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
   array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
   fs->Write( info, 0, info->Length );
}

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Delete the file if it exists.
   if ( File::Exists( path ) )
   {
      File::Delete( path );
   }

   //Create the file.
   {
      FileStream^ fs = File::Create( path );
      try
      {
         AddText( fs, "This is some text" );
         AddText( fs, "This is some more text," );
         AddText( fs, "\r\nand this is on a new line" );
         AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n" );
         for ( int i = 1; i < 120; i++ )
         {
            AddText( fs, Convert::ToChar( i ).ToString() );
            
            //Split the output at every 10th character.
            if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
            {
               AddText( fs, "\r\n" );
            }
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
   
   //Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      try
      {
         array<Byte>^b = gcnew array<Byte>(1024);
         UTF8Encoding^ temp = gcnew UTF8Encoding( true );
         while ( fs->Read( b, 0, b->Length ) > 0 )
         {
            Console::WriteLine( temp->GetString( b ) );
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
}
using System;
using System.IO;
using System.Text;

class Test
{

    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        //Create the file.
        using (FileStream fs = File.Create(path))
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++)
            {
                AddText(fs, Convert.ToChar(i).ToString());

            }
        }

        //Open the stream and read it back.
        using (FileStream fs = File.OpenRead(path))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }

    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}
Imports System
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        ' Delete the file if it exists.
        If File.Exists(path) Then
            File.Delete(path)
        End If

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:" & Environment.NewLine)

        Dim i As Integer

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) As Byte
        Dim temp As UTF8Encoding = New UTF8Encoding(True)

        Do While fs.Read(b, 0, b.Length) > 0
            Console.WriteLine(temp.GetString(b))
        Loop

        fs.Close()
    End Sub

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
End Class

下列範例顯示如何以非同步方式寫入檔案。The following example shows how to write to a file asynchronously. 此程式碼會在具有名為 Userinput> 之 TextBlock 的 WPF 應用程式中執行, 並將按鈕連結至名為 Button_Click 的 Click 事件處理常式。This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. 檔案路徑必須變更為存在於電腦上的檔案。The file path needs to be changed to a file that exists on the computer.

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

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

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            UnicodeEncoding uniencoding = new UnicodeEncoding();
            string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";
           
            byte[] result = uniencoding.GetBytes(UserInput.Text);
            
            using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
            {
                SourceStream.Seek(0, SeekOrigin.End);
                await SourceStream.WriteAsync(result, 0, result.Length);
            }
        }
    }
}
Imports System.IO
Imports System.Text

Class MainWindow
    Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim uniencoding As UnicodeEncoding = New UnicodeEncoding()
        Dim filename As String = "c:\Users\exampleuser\Documents\userinputlog.txt"

        Dim result As Byte() = uniencoding.GetBytes(UserInput.Text)

        Using SourceStream As FileStream = File.Open(filename, FileMode.OpenOrCreate)
            SourceStream.Seek(0, SeekOrigin.End)
            Await SourceStream.WriteAsync(result, 0, result.Length)
        End Using
    End Sub
End Class

備註

您可以使用類別來讀取、寫入、開啟和關閉檔案系統上的檔案, 以及操作其他檔案相關的作業系統控制碼, 包括管道、標準輸入和標準輸出。 FileStreamUse the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. 您可以使用Read Write WriteAsync ReadAsync CopyToAsync、、和Flush方法來執行同步作業, 或是使用、、和FlushAsync方法來執行非同步作業。 CopyTo業務.You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations. 使用非同步方法來執行耗用大量資源的檔案作業, 而不封鎖主要執行緒。Use the asynchronous methods to perform resource-intensive file 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. FileStream緩衝輸入和輸出以獲得更好的效能。FileStream buffers input and output for better performance.

重要

這個型IDisposable別會執行介面。This type implements the IDisposable interface. 當您完成使用類型時, 您應該直接或間接處置它。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接Dispose處置類型, 請try / catch在區塊中呼叫其方法。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.

IsAsync屬性會偵測檔案控制代碼是否以非同步方式開啟。The IsAsync property detects whether the file handle was opened asynchronously. FileStream您使用isAsync具有、 useAsyncoptions參數的函式建立類別的實例時, 可以指定這個值。You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. 當屬性為時true, 資料流程會利用重迭 i/o 來非同步執行檔案作業。When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously. 不過IsAsync , 屬性不一定ReadAsync true要呼叫、 WriteAsyncCopyToAsync方法。However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. 當屬性為false且您呼叫非同步讀取和寫入作業時, UI 執行緒仍不會被封鎖, 但實際的 i/o 作業會以同步方式執行。 IsAsyncWhen the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.

Seek方法支援隨機存取檔案。The Seek method supports random access to files. Seek允許將讀取/寫入位置移到檔案內的任何位置。Seek allows the read/write position to be moved to any position within the file. 這是使用位元組位移參考點參數來完成。This is done with byte offset reference point parameters. 位元組位移是相對於搜尋參考點, 可以是開頭、目前位置或基礎檔案的結尾, 如SeekOrigin列舉的三個成員所表示。The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration.

注意

磁片檔案一律支援隨機存取。Disk files always support random access. 在建立時, CanSeek屬性值會設為truefalse , 視基礎檔案類型而定。如果基礎檔案類型為 FILE_TYPE_DISK (如 winbase 中所定義), CanSeek則屬性值為。 trueAt the time of construction, the CanSeek property value is set to true or false depending on the underlying file type.If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property value is true. 否則, CanSeek屬性值為falseOtherwise, the CanSeek property value is false.

如果進程在鎖定的部分檔案中終止, 或關閉具有未處理鎖定的檔案, 則行為是未定義的。If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

如需目錄作業和其他檔案作業, 請File參閱Directory、和Path類別。For directory operations and other file operations, see the File, Directory, and Path classes. 類別是一種公用程式類別, 主要是用來根據檔案路徑FileStream建立物件的靜態方法。 FileThe File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. 類別會從位元組陣列建立資料流程, 與FileStream類別類似。 MemoryStreamThe MemoryStream class creates a stream from a byte array and is similar to the FileStream class.

如需常見的檔案和目錄作業清單, 請參閱一般 i/o工作。For a list of common file and directory operations, see Common I/O Tasks.

偵測資料流程位置變更Detection of Stream Position Changes

FileStream當物件在其控制碼上沒有獨佔的保存時, 另一個執行緒可以同時存取該檔案控制代碼, 並變更與檔案控制代碼相關聯之作業系統檔案指標的位置。When a FileStream object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. 在此情況下, FileStream物件中快取的位置和緩衝區中快取的資料可能會遭到入侵。In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. 物件會定期對存取快取緩衝區的方法執行檢查, 以確保作業系統的控制碼位置與FileStream物件所使用的快取位置相同。 FileStreamThe FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the FileStream object.

如果在Read方法的呼叫中偵測到控制碼位置發生非預期的變更, .NET Framework 會捨棄緩衝區的內容, 並再次從檔案讀取資料流程。If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. 這可能會影響效能, 視檔案大小和任何可能影響檔案資料流程位置的其他進程而定。This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.

如果在Write方法的呼叫中偵測到控制碼位置發生非預期的變更, 則會捨棄緩衝區的內容, IOException並擲回例外狀況。If an unexpected change in the handle position is detected in a call to the Write method, the contents of the buffer are discarded and an IOException exception is thrown.

當存取SafeFileHandle屬性來SafeFileHandle FileStream公開控制碼, 或物件在其函式中被指定屬性時,物件在其控制碼上不會有獨佔的保存。FileStreamA FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

建構函式

FileStream(IntPtr, FileAccess) FileStream(IntPtr, FileAccess) FileStream(IntPtr, FileAccess) FileStream(IntPtr, FileAccess)

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream(IntPtr, FileAccess, Boolean) FileStream(IntPtr, FileAccess, Boolean) FileStream(IntPtr, FileAccess, Boolean) FileStream(IntPtr, FileAccess, Boolean)

使用指定的讀取/寫入權限和 FileStream 執行個體擁有權,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.

FileStream(IntPtr, FileAccess, Boolean, Int32) FileStream(IntPtr, FileAccess, Boolean, Int32) FileStream(IntPtr, FileAccess, Boolean, Int32) FileStream(IntPtr, FileAccess, Boolean, Int32)

使用指定的讀取/寫入權限、FileStream 執行個體擁有權和緩衝區大小,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, and buffer size.

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean) FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)

使用指定的讀取/寫入權限、FileStream 執行個體擁有權、緩衝區大小和同步或非同步狀態,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, buffer size, and synchronous or asynchronous state.

FileStream(SafeFileHandle, FileAccess) FileStream(SafeFileHandle, FileAccess) FileStream(SafeFileHandle, FileAccess) FileStream(SafeFileHandle, FileAccess)

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream(SafeFileHandle, FileAccess, Int32) FileStream(SafeFileHandle, FileAccess, Int32) FileStream(SafeFileHandle, FileAccess, Int32) FileStream(SafeFileHandle, FileAccess, Int32)

使用指定的讀取/寫入權限和緩衝區大小,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.

FileStream(SafeFileHandle, FileAccess, Int32, Boolean) FileStream(SafeFileHandle, FileAccess, Int32, Boolean) FileStream(SafeFileHandle, FileAccess, Int32, Boolean) FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

使用指定的讀取/寫入權限、緩衝區大小和同步或非同步狀態,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode) FileStream(String, FileMode) FileStream(String, FileMode) FileStream(String, FileMode)

使用指定的路徑和建立模式初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path and creation mode.

FileStream(String, FileMode, FileAccess) FileStream(String, FileMode, FileAccess) FileStream(String, FileMode, FileAccess) FileStream(String, FileMode, FileAccess)

使用指定路徑、建立模式和讀取/寫入權限,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

FileStream(String, FileMode, FileAccess, FileShare) FileStream(String, FileMode, FileAccess, FileShare) FileStream(String, FileMode, FileAccess, FileShare) FileStream(String, FileMode, FileAccess, FileShare)

使用指定路徑、建立模式、讀取/寫入權限和共用權限,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

FileStream(String, FileMode, FileAccess, FileShare, Int32) FileStream(String, FileMode, FileAccess, FileShare, Int32) FileStream(String, FileMode, FileAccess, FileShare, Int32) FileStream(String, FileMode, FileAccess, FileShare, Int32)

使用指定路徑、建立模式、讀取/寫入與共用權限與緩衝區大小,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.

FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)

使用指定路徑、建立模式、讀取/寫入與共用權限、緩衝大小與同步或非同步狀態,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)

使用指定的路徑、建立模式、讀取/寫入與共用權限、其他 FileStream 對同一檔案的存取權、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小、其他檔案選項、存取控制和稽核安全性,初始化 FileStream 類別的新執行個體。Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.

屬性

CanRead CanRead CanRead CanRead

取得值,表示目前資料流是否支援讀取。Gets a value that indicates whether the current stream supports reading.

CanSeek CanSeek CanSeek CanSeek

取得值,表示目前資料流是否支援搜尋。Gets a value that indicates whether the current stream supports seeking.

CanTimeout CanTimeout CanTimeout CanTimeout

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

(Inherited from Stream)
CanWrite CanWrite CanWrite CanWrite

取得值,表示目前資料流是否支援寫入。Gets a value that indicates whether the current stream supports writing.

Handle Handle Handle Handle

取得目前 FileStream 物件封裝之檔案的作業系統檔案控制代碼。Gets the operating system file handle for the file that the current FileStream object encapsulates.

IsAsync IsAsync IsAsync IsAsync

取得值,指出 FileStream 是以非同步或同步方式開啟。Gets a value that indicates whether the FileStream was opened asynchronously or synchronously.

Length Length Length Length

取得資料流的位元組長度。Gets the length in bytes of the stream.

Name Name Name Name

取得在 FileStream 中開啟之檔案的絕對路徑。Gets the absolute path of the file opened in the FileStream.

Position Position Position Position

取得或設定這個資料流的目前位置。Gets or sets the current position of this stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

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

(Inherited from Stream)
SafeFileHandle SafeFileHandle SafeFileHandle SafeFileHandle

取得 SafeFileHandle 物件,這個物件代表目前的 FileStream 物件封裝之檔案的作業系統檔案控制代碼。Gets a SafeFileHandle object that represents the operating system file handle for the file that the current FileStream object encapsulates.

WriteTimeout WriteTimeout WriteTimeout WriteTimeout

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

(Inherited from Stream)

方法

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

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

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

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

Close() Close() Close() Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.

CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

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

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

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

(Inherited from Stream)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

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

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken)

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

(Inherited from Stream)
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

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

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken)

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

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

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

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

配置 WaitHandle 物件。Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

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

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

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

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()

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

EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

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

EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

結束非同步寫入作業並封鎖,直到 I/O 作業完成。Ends an asynchronous write operation and blocks until the I/O operation is complete. (請考慮用 WriteAsync(Byte[], Int32, Int32, CancellationToken) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32, CancellationToken) instead.)

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

確認釋出資源,並在記憶體回收行程再利用 FileStream 時執行其他清除作業。Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the FileStream.

Flush() Flush() Flush() Flush()

清除這個資料流的緩衝區,讓所有緩衝資料全部寫入檔案。Clears buffers for this stream and causes any buffered data to be written to the file.

Flush(Boolean) Flush(Boolean) Flush(Boolean) Flush(Boolean)

清除此資料流的緩衝區,讓所有緩衝資料全部寫入檔案,同時也清除所有的中繼檔案緩衝區。Clears buffers for this stream and causes any buffered data to be written to the file, and also clears all intermediate file buffers.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

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

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)

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

GetAccessControl() GetAccessControl() GetAccessControl() GetAccessControl()

取得 FileSecurity 物件,該物件會封裝目前 FileStream 物件所描述的檔案之存取控制清單 (ACL) 項目。Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileStream object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

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

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

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

(Inherited from MarshalByRefObject)
Lock(Int64, Int64) Lock(Int64, Int64) Lock(Int64, Int64) Lock(Int64, Int64)

防止其他處理程序讀取或寫入 FileStreamPrevents other processes from reading from or writing to the FileStream.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

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

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

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

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

從資料流讀取位元組區塊,並將資料寫入指定緩衝區。Reads a block of bytes from the stream and writes the data in a given buffer.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)

從目前的檔案資料流讀取位元組序列,並依讀取的位元組數將檔案資料流中位置往前移。Reads a sequence of bytes from the current file stream and advances the position within the file stream by the number of bytes read.

ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) 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.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入位元組陣列 (從指定的位移開始)、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。Asynchronously reads a sequence of bytes from the current file stream and writes them to a byte array beginning at a specified offset, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)

以非同步方式從目前的檔案資料流讀取位元組序列、將其寫入記憶體區域、依讀取的位元組數將檔案資料流中位置往前移,並監視取消要求。Asynchronously reads a sequence of bytes from the current file stream and writes them to a memory region, advances the position within the file stream by the number of bytes read, and monitors cancellation requests.

ReadByte() ReadByte() ReadByte() ReadByte()

從檔案讀取一個位元組,並將讀取位置前移一個位元組。Reads a byte from the file and advances the read position one byte.

Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

設定這個資料流的目前位置為指定的數值。Sets the current position of this stream to the given value.

SetAccessControl(FileSecurity) SetAccessControl(FileSecurity) SetAccessControl(FileSecurity) SetAccessControl(FileSecurity)

FileSecurity 物件所描述的存取控制清單 (ACL) 項目套用至目前 FileStream 物件所描述的檔案。Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileStream object.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

設定這個資料流長度為指定的數值。Sets the length of this stream to the given value.

ToString() ToString() ToString() ToString()

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

(Inherited from Object)
Unlock(Int64, Int64) Unlock(Int64, Int64) Unlock(Int64, Int64) Unlock(Int64, Int64)

允許其他處理序存取先前鎖定之檔案的全部或一部分。Allows access by other processes to all or part of a file that was previously locked.

Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

將位元組區塊寫入檔案資料流中。Writes a block of bytes to the file stream.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)

將位元組序列從唯讀範圍寫入目前的檔案資料流,並依寫入的位元組數將此檔案資料流中目前位置往前移。Writes a sequence of bytes from a read-only span to the current file stream and advances the current position within this file stream by the number of bytes written.

WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) 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.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) 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) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步方式將位元組序列從記憶體區域寫入目前的檔案資料流、依寫入的位元組數將此檔案資料流中目前位置往前移,並監視取消要求。Asynchronously writes a sequence of bytes from a memory region to the current file stream, advances the current position within this file stream by the number of bytes written, and monitors cancellation requests.

WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

寫入一個位元組到檔案資料流中的目前位置。Writes a byte to the current position in the file stream.

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

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

(Inherited from Stream)

擴充方法

GetAccessControl(FileStream) GetAccessControl(FileStream) GetAccessControl(FileStream) GetAccessControl(FileStream)
SetAccessControl(FileStream, FileSecurity) SetAccessControl(FileStream, FileSecurity) SetAccessControl(FileStream, FileSecurity) SetAccessControl(FileStream, FileSecurity)
AsInputStream(Stream) AsInputStream(Stream) AsInputStream(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) AsOutputStream(Stream) AsOutputStream(Stream) 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) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream) AsRandomAccessStream(Stream)

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

適用於

另請參閱