FileStream 類別

定義

提供檔案 的 A Stream ,支援同步與非同步讀寫操作。

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

範例

以下範例展示了部分 FileStream 構造子。

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);
            int readLen;
            while ((readLen = fs.Read(b,0,b.Length)) > 0)
            {
                Console.WriteLine(temp.GetString(b,0,readLen));
            }
        }
    }

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

let addText (fs:FileStream) (value: string) =
    let info = UTF8Encoding(true).GetBytes value
    fs.Write(info, 0, info.Length);

let path = @"c:\temp\MyTest.txt"

// Delete the file if it exists.
if File.Exists path then
    File.Delete path

//Create the file.
do
    use 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 i = 1 to 119 do
        Convert.ToChar i
        |> string
        |> addText fs
    
do
    //Open the stream and read it back.
    use fs = File.OpenRead path
    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true
    let mutable readLen = fs.Read(b,0,b.Length);
    while readLen> 0 do
        printfn $"{temp.GetString(b,0,readLen)}"
        readLen <- fs.Read(b,0,b.Length)
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(1023) 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

以下範例展示了如何非同步寫入檔案。 這段程式碼運行在一個WPF應用程式中,該應用程式有一個名為 UserInput 的 TextBlock 和一個連接到名為 Button_Click 的 Click 事件處理程式的按鈕。 檔案路徑需要改成電腦上存在的檔案。

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

備註

欲了解更多關於此 API 的資訊,請參閱 FileStream 的補充 API 備註

建構函式

名稱 Description
FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
已淘汰.
已淘汰.
已淘汰.

初始化指定檔案句柄的新實例 FileStream ,並具備指定的讀寫權限、 FileStream 實例擁有權、緩衝區大小,以及同步或非同步狀態。

FileStream(IntPtr, FileAccess, Boolean, Int32)
已淘汰.
已淘汰.
已淘汰.

初始化指定檔案柄的新實例 FileStream ,並依照指定的讀寫權限、 FileStream 實例所有權及緩衝區大小。

FileStream(IntPtr, FileAccess, Boolean)
已淘汰.
已淘汰.
已淘汰.

初始化指定檔案柄的新實例 FileStream ,並擁有指定的讀寫權限與 FileStream 實例所有權。

FileStream(IntPtr, FileAccess)
已淘汰.
已淘汰.
已淘汰.

初始化該類別的新實例 FileStream ,以指定的檔案柄,並取得指定的讀寫權限。

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

初始化指定檔案帳柄的新實例 FileStream ,並以指定的讀寫權限、緩衝區大小及同步或非同步狀態。

FileStream(SafeFileHandle, FileAccess, Int32)

初始化指定檔案柄的新類別實例 FileStream ,並依照指定的讀寫權限及緩衝區大小。

FileStream(SafeFileHandle, FileAccess)

初始化該類別的新實例 FileStream ,以指定的檔案柄,並取得指定的讀寫權限。

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

初始化類別的新實例 FileStream ,包含指定的路徑、建立模式、讀寫與共享權限、緩衝區大小,以及同步或非同步狀態。

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

初始化類別的新實例 FileStream ,包含指定的路徑、建立模式、讀寫與共享權限、其他 FileStream 對同一檔案的存取權限、緩衝區大小及額外檔案選項。

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

初始化類別的新實例 FileStream ,包含指定的路徑、建立模式、讀寫與共享權限,以及緩衝區大小。

FileStream(String, FileMode, FileAccess, FileShare)

初始化一個新實例 FileStream ,包含指定的路徑、建立模式、讀寫權限及共享權限。

FileStream(String, FileMode, FileAccess)

以指定的路徑、建立模式及讀寫權限初始化該類別的新實例 FileStream

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

初始化一個新實例, FileStream 包含指定的路徑、建立模式、存取權限與共享權限、緩衝區大小、額外檔案選項、存取控制及稽核安全性。

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

初始化類別的新實例 FileStream ,包含指定的路徑、建立模式、存取權限與共享權限、緩衝區大小及額外檔案選項。

FileStream(String, FileMode)

初始化一個以指定路徑與建立模式的新類別實例 FileStream

FileStream(String, FileStreamOptions)

初始化一個新的類別實例 FileStream ,包含指定的路徑、建立模式、讀寫與分享權限、緩衝區大小、額外檔案選項、預配置大小,以及其他檔案流對同一檔案的存取權限。

屬性

名稱 Description
CanRead

會得到一個值,表示目前串流是否支援讀取。

CanSeek

會得到一個值,表示目前串流是否支援尋道。

CanTimeout

取得值,這個值會判斷目前的數據流是否可以逾時。

(繼承來源 Stream)
CanWrite

會得到一個值,表示目前串流是否支援寫入。

Handle
已淘汰.
已淘汰.
已淘汰.

取得目前 FileStream 物件所封裝檔案的作業系統檔案柄。

IsAsync

會得到一個值,表示是 FileStream 非同步還是同步開啟。

Length

取得數據流的位元組長度。

Name

取得檔案在 FileStream.

Position

取得或設定該串流的當前位置。

ReadTimeout

會取得或設定一個以毫秒為單位的值,決定串流在逾時前嘗試讀取的時間長短。

(繼承來源 Stream)
SafeFileHandle

取得 SafeFileHandle 一個物件,代表該 FileStream 物件所封裝的檔案作業系統的檔案柄。

WriteTimeout

取得或設定一個毫秒級的值,決定串流在逾時前嘗試寫入的時間長短。

(繼承來源 Stream)

方法

名稱 Description
BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始異步讀取作業。 請考慮改用 ReadAsync(Byte[], Int32, Int32, CancellationToken)

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

開始異步寫入作業。 請考慮改用 WriteAsync(Byte[], Int32, Int32, CancellationToken)

Close()

關閉目前串流並釋放與目前串流相關的資源(如套接字和檔案柄)。

Close()

關閉目前串流並釋放與目前串流相關的資源(如套接字和檔案柄)。 與其呼叫此方法,不如確保溪流已被妥善處理。

(繼承來源 Stream)
CopyTo(Stream, Int32)

從目前串流讀取位元組,並依指定緩衝區大小寫入另一串流。 兩個串流的位置依複製的位元組數前進。

CopyTo(Stream, Int32)

從目前串流讀取位元組,並依指定緩衝區大小寫入另一串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyTo(Stream)

從目前串流讀取位元組,然後寫入另一條串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消標記,以異步方式從目前數據流讀取位元組,並將其寫入另一個數據流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消標記,以異步方式從目前的檔案數據流讀取位元組,並將其寫入另一個數據流。

CopyToAsync(Stream, Int32, CancellationToken)

非同步地從目前串流讀取位元組,並使用指定的緩衝區大小與取消標記寫入另一串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

非同步讀取目前串流的位元組,並以指定的緩衝區大小寫入另一串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CopyToAsync(Stream)

非同步地從目前串流讀取位元組,然後寫入另一條串流。 兩個串流的位置依複製的位元組數前進。

(繼承來源 Stream)
CreateObjRef(Type)

建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已淘汰.
已淘汰.
已淘汰.

分配一個 WaitHandle 物件。

(繼承來源 Stream)
Dispose()

釋放 Stream所使用的所有資源。

(繼承來源 Stream)
Dispose(Boolean)

釋放 未管理的資源, FileStream 並可選擇性地釋放受管理資源。

DisposeAsync()

非同步釋放 FileStream.

EndRead(IAsyncResult)

等待即將完成的非同步讀取操作。 (考慮改用 ReadAsync(Byte[], Int32, Int32, CancellationToken) 。)

EndWrite(IAsyncResult)

結束非同步寫入操作並阻塞直到 I/O 操作完成。 (考慮改用 WriteAsync(Byte[], Int32, Int32, CancellationToken) 。)

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

確保當垃圾回收器 FileStream回收時,資源被釋放並執行其他清理作業。

Flush()

清除此數據流的緩衝區,並導致任何緩衝的數據寫入檔案。

Flush(Boolean)

清除此數據流的緩衝區,並導致任何緩衝的數據寫入檔案,並清除所有中繼檔案緩衝區。

FlushAsync()

非同步清除此串流的所有緩衝區,並使任何緩衝資料寫入底層裝置。

(繼承來源 Stream)
FlushAsync(CancellationToken)

非同步清除此串流的所有緩衝區,將任何緩衝資料寫入檔案,並監控取消請求。

GetAccessControl()

取得 FileSecurity 一個封裝該檔案 FileStream 存取控制清單(ACL)條目的物件。

GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個實例存留期原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetType()

取得目前實例的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個實例的存留期原則。

(繼承來源 MarshalByRefObject)
Lock(Int64, Int64)

防止其他程序從 讀取或寫入 FileStream

MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 對象的淺層複本。

(繼承來源 MarshalByRefObject)
ObjectInvariant()
已淘汰.

提供 。Contract

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

從串流讀取一個位元組區塊,並在指定緩衝區寫入資料。

Read(Span<Byte>)

從目前檔案串流讀取一串位元組,並依讀取位元組數推進檔案流中的位置。

Read(Span<Byte>)

在衍生類別中覆寫時,從目前數據流讀取位元組序列,並將數據流中的位置依讀取的位元組數目往前移。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式從目前的檔案數據流讀取位元組序列,並將其寫入位元組陣列,從指定的位移開始,依讀取的位元組數目將檔案數據流中的位置往前移,並監視取消要求。

ReadAsync(Byte[], Int32, Int32)

非同步讀取當前串流的位元組序列,並依讀取位元組數推進串流中的位置。

(繼承來源 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

非同步讀取目前檔案串流中的一串位元組並將其寫入記憶體區域,依讀取位元組數推進檔案串流中的位置,並監控取消請求。

ReadAsync(Memory<Byte>, CancellationToken)

非同步讀取目前串流的位元組序列,依讀取位元組數前進串流中的位置,並監控取消請求。

(繼承來源 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

從目前數據流讀取至少一個字節數目,並將數據流中的位置依讀取的位元組數目往前移。

(繼承來源 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

以異步方式從目前數據流讀取至少一個字節數目、依讀取的位元組數目將數據流中的位置往前移,並監視取消要求。

(繼承來源 Stream)
ReadByte()

從檔案讀取一個位元組,並將讀取位置往前推進一個位元組。

ReadExactly(Byte[], Int32, Int32)

從目前串流讀取 count 位元組數,並推進串流中的位置。

(繼承來源 Stream)
ReadExactly(Span<Byte>)

從目前串流讀取位元組,並推進串流中的位置直到填 buffer 滿。

(繼承來源 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

非同步讀取 count 當前串流的位元組數量,推進串流中的位置,並監控取消請求。

(繼承來源 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

非同步讀取目前串流的位元組,推進串流中的位置直到填 buffer 滿,並監控取消請求。

(繼承來源 Stream)
Seek(Int64, SeekOrigin)

將此串流的當前位置設定為給定值。

SetAccessControl(FileSecurity)

將物件描述 FileSecurity 的存取控制清單(ACL)條目套用到目前 FileStream 物件所描述的檔案上。

SetLength(Int64)

將此串流的長度設定為給定值。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)
Unlock(Int64, Int64)

允許其他進程存取先前鎖定之檔案的所有或部分。

Write(Byte[], Int32, Int32)

將一個位元組區塊寫入檔案串流。

Write(ReadOnlySpan<Byte>)

從唯讀區間寫入一串位元組到目前的檔案串流,並依照寫入的位元組數將該檔案串流中的當前位置往前推進。

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將位元組序列寫入目前數據流,並依寫入的位元組數目將這個數據流中的目前位置往前移。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

非同步地將一串位元組寫入目前串流,依照寫入位元組數將該串流中的當前位置前進,並監控取消請求。

WriteAsync(Byte[], Int32, Int32)

非同步地將一串位元組寫入目前串流,並依照寫入的位元組數將該串流中的當前位置往前推進。

(繼承來源 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

非同步地從記憶體區域寫入一串位元組到目前的檔案串流,依照寫入的位元組數將該檔案串流中的當前位置往前推進,並監控取消請求。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

非同步地將一串位元組寫入目前串流,依照寫入位元組數將該串流中的當前位置前進,並監控取消請求。

(繼承來源 Stream)
WriteByte(Byte)

會將一個位元組寫入檔案串流的當前位置。

明確介面實作

名稱 Description
IDisposable.Dispose()

釋放 Stream所使用的所有資源。

(繼承來源 Stream)

擴充方法

名稱 Description
AsInputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的 Managed 資料流轉換為 Windows 執行時間中的輸入資料流。

AsOutputStream(Stream)

將適用於 Windows 市集應用程式的 .NET 中的 Managed 資料流轉換為 Windows 執行時間中的輸出資料流。

AsRandomAccessStream(Stream)

將指定的數據流轉換為隨機存取數據流。

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從異步可處置專案傳回的工作等候。

CopyToAsync(Stream, PipeWriter, CancellationToken)

非同步讀取 的 Stream 位元組並使用消去標記寫入指定的 PipeWriter

GetAccessControl(FileStream)

傳回檔案的安全性資訊。

SetAccessControl(FileStream, FileSecurity)

變更現有檔案的安全性屬性。

適用於

另請參閱