FileStream 建構函式

定義

初始化 FileStream 類別的新執行個體。

多載

FileStream(SafeFileHandle, FileAccess)

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

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

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小、其他檔案選項、存取控制和稽核安全性,初始化 FileStream 類別的新執行個體。

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

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。

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

使用指定的路徑、建立模式、讀取/寫入與共用權限、其他 FileStream 對同一檔案的存取權、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。

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

使用指定路徑、建立模式、讀取/寫入與共用權限與緩衝區大小,初始化 FileStream 類別的新執行個體。

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

使用指定的讀取/寫入權限、FileStream 執行個體擁有權、緩衝區大小和同步或非同步狀態,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

FileStream(String, FileMode, FileAccess, FileShare)

使用指定路徑、建立模式、讀取/寫入權限和共用權限,初始化 FileStream 類別的新執行個體。

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

使用指定的讀取/寫入權限、FileStream 執行個體擁有權和緩衝區大小,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

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

使用指定路徑、建立模式、讀取/寫入與共用權限、緩衝大小與同步或非同步狀態,初始化 FileStream 類別的新執行個體。

FileStream(String, FileMode, FileAccess)

使用指定路徑、建立模式和讀取/寫入權限,初始化 FileStream 類別的新執行個體。

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

使用指定的讀取/寫入權限和 FileStream 執行個體擁有權,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

FileStream(SafeFileHandle, FileAccess, Int32)

使用指定的讀取/寫入權限和緩衝區大小,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

使用指定的讀取/寫入權限、緩衝區大小和同步或非同步狀態,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。

FileStream(String, FileStreamOptions)

使用指定的路徑、建立模式、讀取/寫入和共用許可權、緩衝區大小、其他檔案選項、預先配置大小,以及其他 FileStreams 的存取權,初始化 類別的新實例 FileStream

FileStream(String, FileMode)

使用指定的路徑和建立模式初始化 FileStream 類別的新執行個體。

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

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

FileStream(SafeFileHandle, FileAccess)

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess)

參數

handle
SafeFileHandle

目前 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

例外狀況

access 不是 FileAccess 的欄位。

呼叫端沒有必要的權限。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

呼叫 時 Close ,控制碼也會關閉,而且檔案的控制碼計數會遞減。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免呼叫您完成控制碼之後以外的 Close 任何方法。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

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

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小、其他檔案選項、存取控制和稽核安全性,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::Security::AccessControl::FileSystemRights rights, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options, System::Security::AccessControl::FileSecurity ^ fileSecurity);
public FileStream (string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity);
new System.IO.FileStream : string * System.IO.FileMode * System.Security.AccessControl.FileSystemRights * System.IO.FileShare * int * System.IO.FileOptions * System.Security.AccessControl.FileSecurity -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, rights As FileSystemRights, share As FileShare, bufferSize As Integer, options As FileOptions, fileSecurity As FileSecurity)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

rights
FileSystemRights

列舉值的位元組合,其決定建立檔案存取和稽核規則時要使用的存取權。

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

options
FileOptions

列舉值的位元組合,其指定其他的檔案選項。

fileSecurity
FileSecurity

物件,其決定檔案的存取控制和稽核安全性。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個不正確字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

bufferSize 為負值或零。

-或-

modeaccessshare 包含無效的值。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

-或-

針對 options 指定了 Encrypted,但目前平台不支援檔案加密。

指定的 path、檔案名稱,或兩者都超出系統定義的長度上限。

目前的作業系統不是 Windows NT 或更新版本。

範例

下列範例會將資料寫入檔案,然後使用 物件讀取資料 FileStream

using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Security::AccessControl;
using namespace System::Security::Principal;

int main()
{
    try
    {
        // Create a file and write data to it.

        // Create an array of bytes.
        array<Byte>^ messageByte =
            Encoding::ASCII->GetBytes("Here is some data.");

        // Specify an access control list (ACL)
        FileSecurity^ fs = gcnew FileSecurity();

        fs->AddAccessRule(
            gcnew FileSystemAccessRule("MYDOMAIN\\MyAccount",
            FileSystemRights::Modify, AccessControlType::Allow));

        // Create a file using the FileStream class.
        FileStream^ fWrite = gcnew FileStream("test.txt",
            FileMode::Create, FileSystemRights::Modify,
            FileShare::None, 8, FileOptions::None, fs);

        // Write the number of bytes to the file.
        fWrite->WriteByte((Byte)messageByte->Length);

        // Write the bytes to the file.
        fWrite->Write(messageByte, 0, messageByte->Length);

        // Close the stream.
        fWrite->Close();

        // Open a file and read the number of bytes.

        FileStream^ fRead = 
            gcnew FileStream("test.txt", FileMode::Open);

        // The first byte is the string length.
        int length = (int)fRead->ReadByte();

        // Create a new byte array for the data.
        array<Byte>^ readBytes = gcnew array<Byte>(length);

        // Read the data from the file.
        fRead->Read(readBytes, 0, readBytes->Length);

        // Close the stream.
        fRead->Close();

        // Display the data.
        Console::WriteLine(Encoding::ASCII->GetString(readBytes));

        Console::WriteLine("Done writing and reading data.");
    }

    catch (IdentityNotMappedException^)
    {
        Console::WriteLine("You need to use your own credentials " +
            " 'MYDOMAIN\\MyAccount'.");
    }

    catch (IOException^ ex)
    {
        Console::WriteLine(ex->Message);
    }
}
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileStreamExample
    {
        public static void Main()
        {
            try
            {
                // Create a file and write data to it.

                // Create an array of bytes.
                byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");

                // Specify an access control list (ACL)
                FileSecurity fs = new FileSecurity();

                fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName",
                                                            FileSystemRights.ReadData,
                                                            AccessControlType.Allow));

                // Create a file using the FileStream class.
                FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs);

                // Write the number of bytes to the file.
                fWrite.WriteByte((byte)messageByte.Length);

                // Write the bytes to the file.
                fWrite.Write(messageByte, 0, messageByte.Length);

                // Close the stream.
                fWrite.Close();

                // Open a file and read the number of bytes.

                FileStream fRead = new FileStream("test.txt", FileMode.Open);

                // The first byte is the string length.
                int length = (int)fRead.ReadByte();

                // Create a new byte array for the data.
                byte[] readBytes = new byte[length];

                // Read the data from the file.
                fRead.Read(readBytes, 0, readBytes.Length);

                // Close the stream.
                fRead.Close();

                // Display the data.
                Console.WriteLine(Encoding.ASCII.GetString(readBytes));

                Console.WriteLine("Done writing and reading data.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
    }
}
open System
open System.IO;
open System.Text
open System.Security.AccessControl;

try
    // Create a file and write data to it.

    // Create an array of bytes.
    let messageByte = Encoding.ASCII.GetBytes "Here is some data."
    // Specify an access control list (ACL)
    let fs = FileSecurity()

    FileSystemAccessRule(@"DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow)
    |> fs.AddAccessRule
    // Create a file using the FileStream class.
    let fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs)

    // Write the number of bytes to the file.
    byte messageByte.Length
    |> fWrite.WriteByte

    // Write the bytes to the file.
    fWrite.Write(messageByte, 0, messageByte.Length);

    // Close the stream.
    fWrite.Close();

    // Open a file and read the number of bytes.

    let fRead = new FileStream("test.txt", FileMode.Open)

    // The first byte is the string length.
    let length = fRead.ReadByte() |> int

    // Create a new byte array for the data.
    let readBytes = Array.zeroCreate length

    // Read the data from the file.
    fRead.Read(readBytes, 0, readBytes.Length);

    // Close the stream.
    fRead.Close();

    // Display the data.
    printfn $"{Encoding.ASCII.GetString readBytes}"
    printfn "Done writing and reading data."

with e ->
    printfn $"{e}"
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl



Module FileStreamExample

    Sub Main()
        Try
            ' Create a file and write data to it.
            ' Create an array of bytes.
            Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.")

            ' Specify an access control list (ACL)
            Dim fs As New FileSecurity()

            fs.AddAccessRule(New FileSystemAccessRule("DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow))

            ' Create a file using the FileStream class.
            Dim fWrite As New FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs)

            ' Write the number of bytes to the file.
            fWrite.WriteByte(System.Convert.ToByte(messageByte.Length))

            ' Write the bytes to the file.
            fWrite.Write(messageByte, 0, messageByte.Length)

            ' Close the stream.
            fWrite.Close()


            ' Open a file and read the number of bytes.
            Dim fRead As New FileStream("test.txt", FileMode.Open)

            ' The first byte is the string length.
            Dim length As Integer = Fix(fRead.ReadByte())

            ' Create a new byte array for the data.
            Dim readBytes(length) As Byte

            ' Read the data from the file.
            fRead.Read(readBytes, 0, readBytes.Length)

            ' Close the stream.
            fRead.Close()

            ' Display the data.
            Console.WriteLine(Encoding.ASCII.GetString(readBytes))

            Console.WriteLine("Done writing and reading data.")
        Catch e As Exception
            Console.WriteLine(e)
        End Try

        Console.ReadLine()

    End Sub
End Module

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

FileStream使用此建構函式在建立檔案時套用存取權限。 若要存取或修改現有檔案的許可權,請考慮使用 GetAccessControlSetAccessControl 方法。

參數 fileOptions 可用來提供建立物件時可運用之更進階作業的 FileStream 存取權。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,這個類別可以存取實體裝置。

CanSeek 適用于 true 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

重要

此建構函式不存在於 .NET Core 中。 相反地,從 .NET Core 3.1 開始,您可以在元件內使用 類別的 System.Security.AccessControl 下列擴充方法 FileSystemAclExtensionsCreate(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

另請參閱

適用於

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

使用指定的路徑、建立模式、存取權與共用權限、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::Security::AccessControl::FileSystemRights rights, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options);
public FileStream (string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);
new System.IO.FileStream : string * System.IO.FileMode * System.Security.AccessControl.FileSystemRights * System.IO.FileShare * int * System.IO.FileOptions -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, rights As FileSystemRights, share As FileShare, bufferSize As Integer, options As FileOptions)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

rights
FileSystemRights

列舉值的位元組合,其決定建立檔案存取和稽核規則時要使用的存取權。

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

options
FileOptions

列舉值的位元組合,其指定其他的檔案選項。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

bufferSize 為負值或零。

-或-

modeaccessshare 包含無效的值。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

目前的作業系統不是 Windows NT 或更新版本。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

-或-

針對 options 指定了 Encrypted,但目前平台不支援檔案加密。

指定的 path、檔案名稱,或兩者都超出系統定義的長度上限。

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

FileStream使用此建構函式在建立檔案時套用存取權限。 若要存取或修改現有檔案的許可權,請考慮使用 GetAccessControlSetAccessControl 方法。

參數 fileOptions 可用來提供更進階作業的存取權,這些作業可在建立 FileStream 物件時加以運用。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,此類別可以存取實體裝置。

CanSeektrue 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

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

使用指定的路徑、建立模式、讀取/寫入與共用權限、其他 FileStream 對同一檔案的存取權、緩衝區大小和其他檔案選項,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int * System.IO.FileOptions -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer, options As FileOptions)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

access
FileAccess

列舉值的位元組合,其決定 FileStream 物件存取檔案的方式。 這也可以判斷 FileStream 物件之 CanReadCanWrite 屬性傳回的值。 如果 path 指定了磁碟檔案,則 CanSeektrue

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

options
FileOptions

列舉值的位元組合,其指定其他的檔案選項。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

bufferSize 為負值或零。

-或-

modeaccessshare 包含無效的值。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

-或-

針對 options 指定了 Encrypted,但目前平台不支援檔案加密。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

範例

下列範例會將資料寫入檔案,然後使用 物件讀取資料 FileStream

#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Security::AccessControl;

int main()
{
    try
    {
        // Create a file and write data to it.

        // Create an array of bytes.
        array<Byte>^ messageByte =
            Encoding::ASCII->GetBytes("Here is some data.");

        // Create a file using the FileStream class.
        FileStream^ fWrite = gcnew FileStream("test.txt", FileMode::Create,
            FileAccess::ReadWrite, FileShare::None, 8, FileOptions::None);

        // Write the number of bytes to the file.
        fWrite->WriteByte((Byte)messageByte->Length);

        // Write the bytes to the file.
        fWrite->Write(messageByte, 0, messageByte->Length);

        // Close the stream.
        fWrite->Close();


        // Open a file and read the number of bytes.

        FileStream^ fRead = gcnew FileStream("test.txt", 
            FileMode::Open);

        // The first byte is the string length.
        int length = (int)fRead->ReadByte();

        // Create a new byte array for the data.
        array<Byte>^ readBytes = gcnew array<Byte>(length);

        // Read the data from the file.
        fRead->Read(readBytes, 0, readBytes->Length);

        // Close the stream.
        fRead->Close();

        // Display the data.
        Console::WriteLine(Encoding::ASCII->GetString(readBytes));

        Console::WriteLine("Done writing and reading data.");
    }
    catch (IOException^ ex)
    {
        Console::WriteLine(ex->Message);
    }
}
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileStreamExample
    {
        public static void Main()
        {
            try
            {
                // Create a file and write data to it.

                // Create an array of bytes.
                byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");

                // Create a file using the FileStream class.
                FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None);

                // Write the number of bytes to the file.
                fWrite.WriteByte((byte)messageByte.Length);

                // Write the bytes to the file.
                fWrite.Write(messageByte, 0, messageByte.Length);

                // Close the stream.
                fWrite.Close();

                // Open a file and read the number of bytes.

                FileStream fRead = new FileStream("test.txt", FileMode.Open);

                // The first byte is the string length.
                int length = (int)fRead.ReadByte();

                // Create a new byte array for the data.
                byte[] readBytes = new byte[length];

                // Read the data from the file.
                fRead.Read(readBytes, 0, readBytes.Length);

                // Close the stream.
                fRead.Close();

                // Display the data.
                Console.WriteLine(Encoding.ASCII.GetString(readBytes));

                Console.WriteLine("Done writing and reading data.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
    }
}
open System.IO
open System.Text

try
    // Create a file and write data to it.

    // Create an array of bytes.
    let messageByte = Encoding.ASCII.GetBytes "Here is some data."

    // Create a file using the FileStream class.
    let fWrite =
        new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None)

    // Write the number of bytes to the file.
    byte messageByte.Length |> fWrite.WriteByte

    // Write the bytes to the file.
    fWrite.Write(messageByte, 0, messageByte.Length)

    // Close the stream.
    fWrite.Close()

    // Open a file and read the number of bytes.

    let fRead = new FileStream("test.txt", FileMode.Open)

    // The first byte is the string length.
    let length = fRead.ReadByte() |> int

    // Create a new byte array for the data.
    let readBytes = Array.zeroCreate length

    // Read the data from the file.
    fRead.Read(readBytes, 0, readBytes.Length) |> ignore

    // Close the stream.
    fRead.Close()

    // Display the data.
    printfn $"{Encoding.ASCII.GetString readBytes}"

    printfn "Done writing and reading data."

with e ->
    printfn $"{e}"
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl



Module FileStreamExample

    Sub Main()
        Try
            ' Create a file and write data to it.
            ' Create an array of bytes.
            Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.")

            ' Create a file using the FileStream class.
            Dim fWrite As New FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None)

            ' Write the number of bytes to the file.
            fWrite.WriteByte(System.Convert.ToByte(messageByte.Length))

            ' Write the bytes to the file.
            fWrite.Write(messageByte, 0, messageByte.Length)

            ' Close the stream.
            fWrite.Close()


            ' Open a file and read the number of bytes.
            Dim fRead As New FileStream("test.txt", FileMode.Open)

            ' The first byte is the string length.
            Dim length As Integer = Fix(fRead.ReadByte())

            ' Create a new byte array for the data.
            Dim readBytes(length) As Byte

            ' Read the data from the file.
            fRead.Read(readBytes, 0, readBytes.Length)

            ' Close the stream.
            fRead.Close()

            ' Display the data.
            Console.WriteLine(Encoding.ASCII.GetString(readBytes))

            Console.WriteLine("Done writing and reading data.")
        Catch e As Exception
            Console.WriteLine(e)
        End Try

        Console.ReadLine()

    End Sub
End Module

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 fileOptions 可用來提供更進階作業的存取權,這些作業可在建立 FileStream 物件時加以運用。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,此類別可以存取實體裝置。

CanSeektrue 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

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

使用指定路徑、建立模式、讀取/寫入與共用權限與緩衝區大小,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

access
FileAccess

列舉值的位元組合,其決定 FileStream 物件存取檔案的方式。 這也可以判斷 FileStream 物件之 CanReadCanWrite 屬性傳回的值。 如果 path 指定了磁碟檔案,則 CanSeektrue

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

bufferSize 為負值或零。

-或-

modeaccessshare 包含無效的值。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,此類別可以存取實體裝置。

CanSeektrue 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

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

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

警告

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

使用指定的讀取/寫入權限、FileStream 執行個體擁有權、緩衝區大小和同步或非同步狀態,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean, bufferSize As Integer, isAsync As Boolean)

參數

handle
IntPtr

nativeint

這個 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

ownsHandle
Boolean

如果這個 FileStream 執行個體將擁有檔案控制代碼,則為 true;否則為 false

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

isAsync
Boolean

如果控制代碼為非同步開啟 (也就是,在重疊 I/O 模式),則為 true;否則為 false

屬性

例外狀況

access 小於 FileAccess.Read 或大於 FileAccess.ReadWrite,或者 bufferSize 小於或等於 0。

控制代碼無效。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

呼叫端沒有必要的權限。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

物件 FileStream 會獲得檔案的指定存取權。 控制碼的擁有權將會如指定。 如果這個 FileStream 擁有控制碼,對 方法的 Close 呼叫也會關閉控制碼。 特別是,檔案的控制碼計數會遞減。 物件 FileStream 會指定指定的緩衝區大小。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免在您使用控制碼完成之後呼叫以外的任何方法 Close 。 或者,在呼叫這個 FileStream 建構函式之前,讀取和寫入控制碼。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(String, FileMode, FileAccess, FileShare)

使用指定路徑、建立模式、讀取/寫入權限和共用權限,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

access
FileAccess

列舉值的位元組合,其決定 FileStream 物件存取檔案的方式。 這也可以判斷 FileStream 物件之 CanReadCanWrite 屬性傳回的值。 如果 path 指定了磁碟檔案,則 CanSeektrue

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

mode 包含無效的值。

範例

此程式碼範例是為 方法提供之較大範例的 Lock 一部分。

FileStream^ fileStream = gcnew FileStream( "Test#@@#.dat",FileMode::OpenOrCreate,FileAccess::ReadWrite,FileShare::ReadWrite );
using(FileStream fileStream = new FileStream(
    "Test#@@#.dat", FileMode.OpenOrCreate,
    FileAccess.ReadWrite, FileShare.ReadWrite))
use fileStream =
    new FileStream("Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim aFileStream As New FileStream( _
    "Test#@@#.dat", FileMode.OpenOrCreate, _
    FileAccess.ReadWrite, FileShare.ReadWrite)

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

建構函式會提供檔案的讀取/寫入存取權,而且會開啟共用讀取存取權 (也就是說,開啟檔案以供這個或其他進程寫入的要求將會失敗,直到 FileStream 物件關閉為止,但讀取嘗試將會成功) 。 緩衝區大小會設定為預設大小 4096 個位元組, (4 KB) 。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,此類別可以存取實體裝置。

CanSeektrue 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(IntPtr, FileAccess, Boolean, Int32)

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

警告

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

使用指定的讀取/寫入權限、FileStream 執行個體擁有權和緩衝區大小,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean, bufferSize As Integer)

參數

handle
IntPtr

nativeint

這個 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

ownsHandle
Boolean

如果這個 FileStream 執行個體將擁有檔案控制代碼,則為 true;否則為 false

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

屬性

例外狀況

bufferSize 為負。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

呼叫端沒有必要的權限。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

物件 FileStream 會獲得檔案的指定存取權。 控制碼的擁有權將會如指定。 如果這個 FileStream 擁有控制碼,對 方法的 Close 呼叫也會關閉控制碼。 特別是,檔案的控制碼計數會遞減。 物件 FileStream 會指定指定的緩衝區大小。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免在您使用控制碼完成之後呼叫以外的任何方法 Close 。 或者,在呼叫這個 FileStream 建構函式之前,讀取和寫入控制碼。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

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

使用指定路徑、建立模式、讀取/寫入與共用權限、緩衝大小與同步或非同步狀態,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize, bool useAsync);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int * bool -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer, useAsync As Boolean)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

access
FileAccess

列舉值的位元組合,其決定 FileStream 物件存取檔案的方式。 這也可以判斷 FileStream 物件之 CanReadCanWrite 屬性傳回的值。 如果 path 指定了磁碟檔案,則 CanSeektrue

share
FileShare

列舉值的位元組合,其決定流程如何共用檔案。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

useAsync
Boolean

指定要使用非同步 I/O 或同步 I/O。 但是,請注意:基礎作業系統可能並不支援非同步 I/O,所以在指定 true 時,可能會視平台以同步方式開啟控制代碼。 在以非同步方式開啟時,BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 方法對大量讀取或寫入的作業會有較佳的效能,但對於少量讀取和寫入的作業卻會比較慢。 如果要將應用程式設計成使用非同步 I/O,請將 useAsync 參數設定為 true。 正確地使用非同步 I/O,可以讓應用程式的執行快上十倍,但如果沒有配合非同步 I/O 的需求重新設計應用程式,卻會降低十倍的效能。

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

bufferSize 為負值或零。

-或-

modeaccessshare 包含無效的值。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

範例

下列程式碼範例示範如何以非同步方式將資料寫入檔案,然後確認資料已正確寫入。 系統會 State 建立 物件,以將資訊從主執行緒傳遞至 EndReadCallbackEndWriteCallback 方法。

using namespace System;
using namespace System::IO;
using namespace System::Threading;

// Maintain state information to be passed to 
// EndWriteCallback and EndReadCallback.
ref class State
{
private:

   // fStream is used to read and write to the file.
   FileStream^ fStream;

   // writeArray stores data that is written to the file.
   array<Byte>^writeArray;

   // readArray stores data that is read from the file.
   array<Byte>^readArray;

   // manualEvent signals the main thread 
   // when verification is complete.
   ManualResetEvent^ manualEvent;

public:
   State( FileStream^ fStream, array<Byte>^writeArray, ManualResetEvent^ manualEvent )
   {
      this->fStream = fStream;
      this->writeArray = writeArray;
      this->manualEvent = manualEvent;
      readArray = gcnew array<Byte>(writeArray->Length);
   }


   property FileStream^ FStream 
   {
      FileStream^ get()
      {
         return fStream;
      }

   }

   property array<Byte>^ WriteArray 
   {
      array<Byte>^ get()
      {
         return writeArray;
      }

   }

   property array<Byte>^ ReadArray 
   {
      array<Byte>^ get()
      {
         return readArray;
      }

   }

   property ManualResetEvent^ ManualEvent 
   {
      ManualResetEvent^ get()
      {
         return manualEvent;
      }

   }

};

ref class FStream
{
private:

   // When BeginRead is finished reading data from the file, the 
   // EndReadCallback method is called to end the asynchronous 
   // read operation and then verify the data.
   static void EndReadCallback( IAsyncResult^ asyncResult )
   {
      State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState);
      int readCount = tempState->FStream->EndRead( asyncResult );
      int i = 0;
      while ( i < readCount )
      {
         if ( tempState->ReadArray[ i ] != tempState->WriteArray[ i++ ] )
         {
            Console::WriteLine( "Error writing data." );
            tempState->FStream->Close();
            return;
         }
      }

      Console::WriteLine( "The data was written to {0} "
      "and verified.", tempState->FStream->Name );
      tempState->FStream->Close();
      
      // Signal the main thread that the verification is finished.
      tempState->ManualEvent->Set();
   }


public:

   // When BeginWrite is finished writing data to the file, the
   // EndWriteCallback method is called to end the asynchronous 
   // write operation and then read back and verify the data.
   static void EndWriteCallback( IAsyncResult^ asyncResult )
   {
      State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState);
      FileStream^ fStream = tempState->FStream;
      fStream->EndWrite( asyncResult );
      
      // Asynchronously read back the written data.
      fStream->Position = 0;
      asyncResult = fStream->BeginRead( tempState->ReadArray, 0, tempState->ReadArray->Length, gcnew AsyncCallback( &FStream::EndReadCallback ), tempState );
      
      // Concurrently do other work, such as 
      // logging the write operation.
   }

};


int main()
{
   
   // Create a synchronization object that gets 
   // signaled when verification is complete.
   ManualResetEvent^ manualEvent = gcnew ManualResetEvent( false );
   
   // Create the data to write to the file.
   array<Byte>^writeArray = gcnew array<Byte>(100000);
   (gcnew Random)->NextBytes( writeArray );
   FileStream^ fStream = gcnew FileStream(  "Test#@@#.dat",FileMode::Create,FileAccess::ReadWrite,FileShare::None,4096,true );
   
   // Check that the FileStream was opened asynchronously.
   Console::WriteLine( "fStream was {0}opened asynchronously.", fStream->IsAsync ? (String^)"" : "not " );
   
   // Asynchronously write to the file.
   IAsyncResult^ asyncResult = fStream->BeginWrite( writeArray, 0, writeArray->Length, gcnew AsyncCallback( &FStream::EndWriteCallback ), gcnew State( fStream,writeArray,manualEvent ) );
   
   // Concurrently do other work and then wait 
   // for the data to be written and verified.
   manualEvent->WaitOne( 5000, false );
}
using System;
using System.IO;
using System.Threading;

class FStream
{
    static void Main()
    {
        // Create a synchronization object that gets
        // signaled when verification is complete.
        ManualResetEvent manualEvent = new ManualResetEvent(false);

        // Create random data to write to the file.
        byte[] writeArray = new byte[100000];
        new Random().NextBytes(writeArray);

        FileStream fStream =
            new FileStream("Test#@@#.dat", FileMode.Create,
            FileAccess.ReadWrite, FileShare.None, 4096, true);

        // Check that the FileStream was opened asynchronously.
        Console.WriteLine("fStream was {0}opened asynchronously.",
            fStream.IsAsync ? "" : "not ");

        // Asynchronously write to the file.
        IAsyncResult asyncResult = fStream.BeginWrite(
            writeArray, 0, writeArray.Length,
            new AsyncCallback(EndWriteCallback),
            new State(fStream, writeArray, manualEvent));

        // Concurrently do other work and then wait
        // for the data to be written and verified.
        manualEvent.WaitOne(5000, false);
    }

    // When BeginWrite is finished writing data to the file, the
    // EndWriteCallback method is called to end the asynchronous
    // write operation and then read back and verify the data.
    static void EndWriteCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        FileStream fStream = tempState.FStream;
        fStream.EndWrite(asyncResult);

        // Asynchronously read back the written data.
        fStream.Position = 0;
        asyncResult = fStream.BeginRead(
            tempState.ReadArray, 0 , tempState.ReadArray.Length,
            new AsyncCallback(EndReadCallback), tempState);

        // Concurrently do other work, such as
        // logging the write operation.
    }

    // When BeginRead is finished reading data from the file, the
    // EndReadCallback method is called to end the asynchronous
    // read operation and then verify the data.
    static void EndReadCallback(IAsyncResult asyncResult)
    {
        State tempState = (State)asyncResult.AsyncState;
        int readCount = tempState.FStream.EndRead(asyncResult);

        int i = 0;
        while(i < readCount)
        {
            if(tempState.ReadArray[i] != tempState.WriteArray[i++])
            {
                Console.WriteLine("Error writing data.");
                tempState.FStream.Close();
                return;
            }
        }
        Console.WriteLine("The data was written to {0} and verified.",
            tempState.FStream.Name);
        tempState.FStream.Close();

        // Signal the main thread that the verification is finished.
        tempState.ManualEvent.Set();
    }

    // Maintain state information to be passed to
    // EndWriteCallback and EndReadCallback.
    class State
    {
        // fStream is used to read and write to the file.
        FileStream fStream;

        // writeArray stores data that is written to the file.
        byte[] writeArray;

        // readArray stores data that is read from the file.
        byte[] readArray;

        // manualEvent signals the main thread
        // when verification is complete.
        ManualResetEvent manualEvent;

        public State(FileStream fStream, byte[] writeArray,
            ManualResetEvent manualEvent)
        {
            this.fStream   = fStream;
            this.writeArray = writeArray;
            this.manualEvent = manualEvent;
            readArray = new byte[writeArray.Length];
        }

        public FileStream FStream
        { get{ return fStream; } }

        public byte[] WriteArray
        { get{ return writeArray; } }

        public byte[] ReadArray
        { get{ return readArray; } }

        public ManualResetEvent ManualEvent
        { get{ return manualEvent; } }
    }
}
open System
open System.IO
open System.Threading

// Maintain state information to be passed to
// EndWriteCallback and EndReadCallback.
type State(fStream: FileStream, writeArray: byte[], manualEvent: ManualResetEvent) =
    // readArray stores data that is read from the file.
    let readArray = Array.zeroCreate writeArray.Length

    member _.FStream = fStream
    member _.WriteArray = writeArray
    member _.ReadArray = readArray
    member _.ManualEvent = manualEvent

// When BeginRead is finished reading data from the file, the
// EndReadCallback method is called to end the asynchronous
// read operation and then verify the data.
let endReadCallback (asyncResult: IAsyncResult) =
    let tempState = asyncResult.AsyncState :?> State
    let readCount = tempState.FStream.EndRead asyncResult

    let mutable i = 0
    let mutable errored = false

    while i < readCount do
        if tempState.ReadArray[i] <> tempState.WriteArray[i] then
            printfn "Error writing data."
            tempState.FStream.Close()
            errored <- true
            i <- readCount

        i <- i + 1

    printfn $"The data was written to {tempState.FStream.Name} and verified."
    tempState.FStream.Close()
    // Signal the main thread that the verification is finished.
    tempState.ManualEvent.Set() |> ignore


// When BeginWrite is finished writing data to the file, the
// EndWriteCallback method is called to end the asynchronous
// write operation and then read back and verify the data.
let endWriteCallback (asyncResult: IAsyncResult) =
    let tempState = asyncResult.AsyncState :?> State
    let fStream = tempState.FStream
    fStream.EndWrite asyncResult

    // Asynchronously read back the written data.
    fStream.Position <- 0

    let asyncResult =
        fStream.BeginRead(tempState.ReadArray, 0, tempState.ReadArray.Length, AsyncCallback endReadCallback, tempState)

    // Concurrently do other work, such as
    // logging the write operation.
    ()


// Create a synchronization object that gets
// signaled when verification is complete.
let manualEvent = new ManualResetEvent false

// Create random data to write to the file.
let writeArray = Array.zeroCreate 100000
Random.Shared.NextBytes writeArray

let fStream =
    new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true)

// Check that the FileStream was opened asynchronously.

if fStream.IsAsync then "" else "not "
|> printfn "fStream was %sopened asynchronously."

// Asynchronously write to the file.
let asyncResult =
    fStream.BeginWrite(
        writeArray,
        0,
        writeArray.Length,
        AsyncCallback endWriteCallback,
        State(fStream, writeArray, manualEvent)
    )

// Concurrently do other work and then wait
// for the data to be written and verified.
manualEvent.WaitOne(5000, false) |> ignore
Imports System.IO
Imports System.Threading

Class FStream

    Shared Sub Main()

        ' Create a synchronization object that gets 
        ' signaled when verification is complete.
        Dim manualEvent As New ManualResetEvent(False)

        ' Create random data to write to the file.
        Dim writeArray(100000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(writeArray)

        Dim fStream As New FileStream("Test#@@#.dat", _
            FileMode.Create, FileAccess.ReadWrite, _
            FileShare.None, 4096, True)

        ' Check that the FileStream was opened asynchronously.
        If fStream.IsAsync = True
            Console.WriteLine("fStream was opened asynchronously.")
        Else
            Console.WriteLine("fStream was not opened asynchronously.")
        End If

        ' Asynchronously write to the file.
        Dim asyncResult As IAsyncResult = fStream.BeginWrite( _
            writeArray, 0, writeArray.Length, _
            AddressOf EndWriteCallback , _
            New State(fStream, writeArray, manualEvent))

        ' Concurrently do other work and then wait
        ' for the data to be written and verified.
        manualEvent.WaitOne(5000, False)
    End Sub

    ' When BeginWrite is finished writing data to the file, the
    ' EndWriteCallback method is called to end the asynchronous 
    ' write operation and then read back and verify the data.
    Private Shared Sub EndWriteCallback(asyncResult As IAsyncResult)
        Dim tempState As State = _
            DirectCast(asyncResult.AsyncState, State)
        Dim fStream As FileStream = tempState.FStream
        fStream.EndWrite(asyncResult)

        ' Asynchronously read back the written data.
        fStream.Position = 0
        asyncResult = fStream.BeginRead( _ 
            tempState.ReadArray, 0 , tempState.ReadArray.Length, _
            AddressOf EndReadCallback, tempState)

        ' Concurrently do other work, such as 
        ' logging the write operation.
    End Sub

    ' When BeginRead is finished reading data from the file, the 
    ' EndReadCallback method is called to end the asynchronous 
    ' read operation and then verify the data.
   Private Shared Sub EndReadCallback(asyncResult As IAsyncResult)
        Dim tempState As State = _
            DirectCast(asyncResult.AsyncState, State)
        Dim readCount As Integer = _
            tempState.FStream.EndRead(asyncResult)

        Dim i As Integer = 0
        While(i < readCount)
            If(tempState.ReadArray(i) <> tempState.WriteArray(i))
                Console.WriteLine("Error writing data.")
                tempState.FStream.Close()
                Return
            End If
            i += 1
        End While

        Console.WriteLine("The data was written to {0} and " & _
            "verified.", tempState.FStream.Name)
        tempState.FStream.Close()

        ' Signal the main thread that the verification is finished.
        tempState.ManualEvent.Set()
    End Sub

    ' Maintain state information to be passed to 
    ' EndWriteCallback and EndReadCallback.
    Private Class State

        ' fStreamValue is used to read and write to the file.
        Dim fStreamValue As FileStream

        ' writeArrayValue stores data that is written to the file.
        Dim writeArrayValue As Byte()

        ' readArrayValue stores data that is read from the file.
        Dim readArrayValue As Byte()

        ' manualEvent signals the main thread 
        ' when verification is complete.
        Dim manualEventValue As ManualResetEvent 

        Sub New(aStream As FileStream, anArray As Byte(), _
            manualEvent As ManualResetEvent)

            fStreamValue     = aStream
            writeArrayValue  = anArray
            manualEventValue = manualEvent
            readArrayValue   = New Byte(anArray.Length - 1){}
        End Sub    

            Public ReadOnly Property FStream() As FileStream
                Get
                    Return fStreamValue
                End Get
            End Property

            Public ReadOnly Property WriteArray() As Byte()
                Get
                    Return writeArrayValue
                End Get
            End Property

            Public ReadOnly Property ReadArray() As Byte()
                Get
                    Return readArrayValue
                End Get
            End Property

            Public ReadOnly Property ManualEvent() As ManualResetEvent
                Get
                    Return manualEventValue
                End Get
            End Property
    End Class 
   
End Class

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,此類別可以存取實體裝置。

CanSeektrue 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

警告

當您使用特定文化設定編譯一組字元,並使用不同的文化設定擷取相同的字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(String, FileMode, FileAccess)

使用指定路徑、建立模式和讀取/寫入權限,初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

access
FileAccess

列舉值的位元組合,其決定 FileStream 物件存取檔案的方式。 這也可以判斷 FileStream 物件之 CanReadCanWrite 屬性傳回的值。 如果 path 指定了磁碟檔案,則 CanSeektrue

例外狀況

pathnull

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個無效字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 access 要求,例如當 accessWriteReadWrite,而檔案或目錄設為唯讀存取時。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

mode 包含無效的值。

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

建構函式具有檔案的讀取/寫入存取權,而且開啟共用讀取存取權 (也就是說,開啟檔案以供寫入的要求將會失敗,直到 FileStream 物件關閉為止,但讀取嘗試將會成功) 。 緩衝區大小會設定為預設大小 4096 位元組, (4 KB) 。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,這個類別可以存取實體裝置。

CanSeek 適用于 true 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(IntPtr, FileAccess, Boolean)

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202

警告

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202

使用指定的讀取/寫入權限和 FileStream 執行個體擁有權,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed.  http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean)

參數

handle
IntPtr

nativeint

目前 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

ownsHandle
Boolean

如果這個 FileStream 執行個體將擁有檔案控制代碼,則為 true;否則為 false

屬性

例外狀況

access 不是 FileAccess 的欄位。

呼叫端沒有必要的權限。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

物件 FileStream 會獲得檔案的指定存取權。 控制碼的擁有權將會如指定。 如果這個進程擁有控制碼,方法的 Close 呼叫也會關閉控制碼,並遞減檔案的控制碼計數。 物件 FileStream 會獲得預設緩衝區大小 4096 個位元組。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免呼叫方法,而不是 Close 使用控制碼完成之後。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(SafeFileHandle, FileAccess, Int32)

使用指定的讀取/寫入權限和緩衝區大小,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access, int bufferSize);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess * int -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess, bufferSize As Integer)

參數

handle
SafeFileHandle

目前 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

FileAccess 常數,它會設定 FileStream 物件的 CanReadCanWrite 屬性。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

例外狀況

handle 參數是無效的控制代碼。

-或-

handle 參數是同步的控制代碼,且曾以非同步方式使用。

bufferSize 參數為負。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

呼叫端沒有必要的權限。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免呼叫您完成控制碼之後以外的 Close 任何方法。 或者,在呼叫這個 FileStream 建構函式之前,先讀取和寫入控制碼。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

使用指定的讀取/寫入權限、緩衝區大小和同步或非同步狀態,初始化指定的檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access, int bufferSize, bool isAsync);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess * int * bool -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess, bufferSize As Integer, isAsync As Boolean)

參數

handle
SafeFileHandle

這個 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

bufferSize
Int32

大於 0 的 Int32 正值,指出緩衝區大小。 預設緩衝區大小為 4096。

isAsync
Boolean

如果控制代碼為非同步開啟 (也就是,在重疊 I/O 模式),則為 true;否則為 false

例外狀況

handle 參數是無效的控制代碼。

-或-

handle 參數是同步的控制代碼,且曾以非同步方式使用。

bufferSize 參數為負。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

呼叫端沒有必要的權限。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

您會將 isAsync 參數設定為 true ,以非同步方式開啟檔案控制碼。 當 參數為 true 時,資料流程會利用重迭的 I/O 以非同步方式執行檔案作業。 不過,參數不需要 true 呼叫 ReadAsyncWriteAsyncCopyToAsync 方法。 isAsync當 參數是 false 且您呼叫非同步讀取和寫入作業時,UI 執行緒仍然不會遭到封鎖,但實際的 I/O 作業會同步執行。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免呼叫您完成控制碼之後以外的 Close 任何方法。 或者,在呼叫這個 FileStream 建構函式之前,先讀取和寫入控制碼。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(String, FileStreamOptions)

使用指定的路徑、建立模式、讀取/寫入和共用許可權、緩衝區大小、其他檔案選項、預先配置大小,以及其他 FileStreams 的存取權,初始化 類別的新實例 FileStream

public:
 FileStream(System::String ^ path, System::IO::FileStreamOptions ^ options);
public FileStream (string path, System.IO.FileStreamOptions options);
new System.IO.FileStream : string * System.IO.FileStreamOptions -> System.IO.FileStream
Public Sub New (path As String, options As FileStreamOptions)

參數

path
String

目前 FileStream 實例將封裝之檔案的相對或絕對路徑。

options
FileStreamOptions

物件,描述要使用的選擇性 FileStream 參數。

例外狀況

pathoptionsnull

path 是空字串、只包含空白字元,或包含一或多個無效字元。

-或-

path 是指 NTFS 環境中的非檔案裝置,例如 CON:COM1:LPT1:

path 是指非 NTFS 環境中的非檔案裝置,例如 CON:COM1:LPT1: 等。

找不到檔案,例如當 ModeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

-或-

磁片在提供時 PreallocationSize 已滿 (,並 path 指向一般檔案) 。

-或-

檔案在提供時 PreallocationSize 太大 (,而且 path 指向一般檔案) 。

呼叫端沒有必要的權限。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的 path 作業系統不允許 Access 要求,例如當 AccessWriteReadWrite,而檔案或目錄設為唯讀存取時。

-或-

Encrypted 針對 Options 指定 ,但目前平臺不支援檔案加密。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

備註

指定 的值 PreallocationSize 可提供預先配置大小的提示,但不是強式保證。 如需完整使用量詳細資料,請參閱 的檔 PreallocationSize

適用於

FileStream(String, FileMode)

使用指定的路徑和建立模式初始化 FileStream 類別的新執行個體。

public:
 FileStream(System::String ^ path, System::IO::FileMode mode);
public FileStream (string path, System.IO.FileMode mode);
new System.IO.FileStream : string * System.IO.FileMode -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode)

參數

path
String

目前 FileStream 物件將會封裝之檔案的相對或絕對路徑。

mode
FileMode

其中一個列舉值,其決定如何開啟或建立檔案。

例外狀況

.NET Framework和 2.1 之前的 .NET Core 版本: path 是空字串 (「」) 、只包含空白字元,或包含一或多個不正確字元。

-或-

path 的參考對象為非檔案裝置,例如 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

path 指非檔案裝置,例如非 NTFS 環境中的 "con:"、"com1:"、"lpt1:" 等等。

pathnull

呼叫端沒有必要的權限。

找不到檔案,例如當 modeFileMode.TruncateFileMode.Open,而且 path 指定的檔案不存在。 這些模式中必須有此檔案。

path 會指定唯讀的檔案。

發生 I/O 錯誤,例如當 path 指定的檔案已存在時指定 FileMode.CreateNew

-或-

資料流已關閉。

指定的路徑無效,例如位於未對應的磁碟機上。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

mode 包含無效的值。

範例

下列程式碼範例示範如何將資料寫入檔案、位元組位元組,然後確認資料已正確寫入。

using namespace System;
using namespace System::IO;
int main()
{
   String^ fileName =  "Test@##@.dat";
   
   // Create random data to write to the file.
   array<Byte>^dataArray = gcnew array<Byte>(100000);
   (gcnew Random)->NextBytes( dataArray );
   FileStream^ fileStream = gcnew FileStream( fileName,FileMode::Create );
   try
   {
      
      // Write the data to the file, byte by byte.
      for ( int i = 0; i < dataArray->Length; i++ )
      {
         fileStream->WriteByte( dataArray[ i ] );

      }
      
      // Set the stream position to the beginning of the file.
      fileStream->Seek( 0, SeekOrigin::Begin );
      
      // Read and verify the data.
      for ( int i = 0; i < fileStream->Length; i++ )
      {
         if ( dataArray[ i ] != fileStream->ReadByte() )
         {
            Console::WriteLine( "Error writing data." );
            return  -1;
         }

      }
      Console::WriteLine( "The data was written to {0} "
      "and verified.", fileStream->Name );
   }
   finally
   {
      fileStream->Close();
   }

}
using System;
using System.IO;

class FStream
{
    static void Main()
    {
        const string fileName = "Test#@@#.dat";

        // Create random data to write to the file.
        byte[] dataArray = new byte[100000];
        new Random().NextBytes(dataArray);

        using(FileStream
            fileStream = new FileStream(fileName, FileMode.Create))
        {
            // Write the data to the file, byte by byte.
            for(int i = 0; i < dataArray.Length; i++)
            {
                fileStream.WriteByte(dataArray[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            // Read and verify the data.
            for(int i = 0; i < fileStream.Length; i++)
            {
                if(dataArray[i] != fileStream.ReadByte())
                {
                    Console.WriteLine("Error writing data.");
                    return;
                }
            }
            Console.WriteLine("The data was written to {0} " +
                "and verified.", fileStream.Name);
        }
    }
}
open System
open System.IO


let fileName = "Test#@@#.dat"

// Create random data to write to the file.
let dataArray = Array.zeroCreate 100000
Random.Shared.NextBytes dataArray

do
    use fileStream = new FileStream(fileName, FileMode.Create)
    // Write the data to the file, byte by byte.
    for i = 0 to dataArray.Length - 1 do
        fileStream.WriteByte dataArray[i]

    // Set the stream position to the beginning of the file.
    fileStream.Seek(0, SeekOrigin.Begin) |> ignore

    // Read and verify the data.
    for i in 0L .. fileStream.Length - 1L do
        if dataArray[int i] <> (fileStream.ReadByte() |> byte) then
            printfn "Error writing data."
            exit 1

    printfn $"The data was written to {fileStream.Name} and verified."
Imports System.IO
Imports System.Text

Class FStream

    Shared Sub Main()

        Const fileName As String = "Test#@@#.dat"

        ' Create random data to write to the file.
        Dim dataArray(100000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(dataArray)

        Dim fileStream As FileStream = _
            new FileStream(fileName, FileMode.Create)
        Try

            ' Write the data to the file, byte by byte.
            For i As Integer = 0 To dataArray.Length - 1
                fileStream.WriteByte(dataArray(i))
            Next i

            ' Set the stream position to the beginning of the stream.
            fileStream.Seek(0, SeekOrigin.Begin)

            ' Read and verify the data.
            For i As Integer = 0 To _
                CType(fileStream.Length, Integer) - 1

                If dataArray(i) <> fileStream.ReadByte() Then
                    Console.WriteLine("Error writing data.")
                    Return
                End If
            Next i
            Console.WriteLine("The data was written to {0} " & _
                "and verified.", fileStream.Name)
        Finally
            fileStream.Close()
        End Try
    
    End Sub
End Class

備註

.NET Framework不支援透過裝置名稱的路徑直接存取實體磁片,例如 「\\.\PHYSICALDRIVE0」。

參數 path 可以是檔案名,包括通用命名慣例上的檔案, (UNC) 共用。

建構函式具有檔案的讀取/寫入存取權,而且開啟共用讀取存取權 (也就是說,開啟檔案以供寫入的要求將會失敗,直到 FileStream 物件關閉為止,但讀取嘗試將會成功) 。

您無法使用此建構函式來開啟唯讀檔案;相反地,您必須使用接受 FileAccess 參數的建構函式,並將值設定為 FileAccess.Read

緩衝區大小會設定為預設大小 4096 位元組, (4 KB) 。

注意

path 不需要是儲存在磁片上的檔案;它可以是支援透過資料流程存取之系統的任何部分。 例如,視系統而定,這個類別可以存取實體裝置。

CanSeek 適用于 true 封裝檔案的所有 FileStream 物件。 如果 path 指出不支援搜尋的裝置, CanSeek 則產生的 FileStream 屬性為 false 。 如需詳細資訊,請參閱 CanSeek

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

對於不含參數的 FileAccess 建構函式,如果 參數設定 Append 為 , Writemode 為預設存取權。 否則,存取權會設定為 ReadWrite

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於

FileStream(IntPtr, FileAccess)

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202

警告

This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.

警告

This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202

使用指定的讀取/寫入權限,初始化指定檔案控制代碼之 FileStream 類別的新執行個體。

public:
 FileStream(IntPtr handle, System::IO::FileAccess access);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
[System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
public FileStream (IntPtr handle, System.IO.FileAccess access);
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated.  Please use new FileStream(SafeFileHandle handle, FileAccess access) instead.  http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess)

參數

handle
IntPtr

nativeint

目前 FileStream 物件將會封裝之檔案的檔案控制代碼。

access
FileAccess

列舉值的位元組合,其設定 FileStream 物件的 CanReadCanWrite 屬性。

屬性

例外狀況

access 不是 FileAccess 的欄位。

呼叫端沒有必要的權限。

發生 I/O 錯誤,例如磁碟錯誤。

-或-

資料流已關閉。

作業系統不允許 access 要求用於指定的檔案控制代碼,例如當 accessWriteReadWrite,而檔案控制代碼設為唯讀存取時。

備註

呼叫 時 Close ,控制碼也會關閉,而且檔案的控制碼計數會遞減。

FileStream 假設它具有控制碼的獨佔控制權。 讀取、寫入或搜尋同時 FileStream 保存控制碼可能會導致資料損毀。 針對資料安全,請在使用控制碼之前呼叫 Flush ,並避免呼叫您完成控制碼之後以外的 Close 任何方法。

警告

當您使用特定文化設定編譯一組字元,並擷取具有不同文化設定的相同字元時,字元可能無法解譯,而且可能會導致擲回例外狀況。

FileShare.Read是沒有 FileShare 參數之建 FileStream 構函式的預設值。

如需一般檔案和目錄作業的清單,請參閱 一般 I/O 工作

另請參閱

適用於