FileStream FileStream FileStream FileStream Constructors

定义

重载

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(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.

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, 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) 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(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(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, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)

使用指定的路径、创建模式、读/写和共享权限、其他 FileStreams 可以具有的对此文件的访问权限、缓冲区大小和附加文件选项初始化 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(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, 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(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(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(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(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(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(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.

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 SafeFileHandle SafeFileHandle SafeFileHandle

当前 FileStream 对象将封装的文件的文件句柄。A file handle for the file that the current FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

异常

access 不是 FileAccess 的字段。access is not a field of FileAccess.

调用方没有所要求的权限。The caller does not have the required permission.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

- 或 --or-

已关闭流。The stream has been closed.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

调用Close时, 句柄也会关闭, 并且文件的句柄计数将减少。When Close is called, the handle is also closed and the file's handle count is decremented.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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

参数

path
String String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

rights
FileSystemRights FileSystemRights FileSystemRights FileSystemRights

一个常数,确定为文件创建访问和审核规则时要使用的访问权。A constant that determines the access rights to use when creating access and audit rules for the file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

options
FileOptions FileOptions FileOptions FileOptions

一个指定附加文件选项的常数。A constant that specifies additional file options.

fileSecurity
FileSecurity FileSecurity FileSecurity FileSecurity

一个常数,确定文件的访问控制和审核安全。A constant that determines the access control and audit security for the file.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

bufferSize 为负数或零。bufferSize is negative or zero.

-or- modeaccessshare 包含无效的值。mode, access, or share contain an invalid value.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

- 或 --or- Encrypted 指定用于 options,但在当前平台上不支持文件加密。Encrypted is specified for options, but file encryption is not supported on the current platform.

指定的 path、文件名或这两者都超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

当前操作系统不是 Windows NT 或更高版本。The current operating system is not Windows NT or later.

示例

下面的示例将数据写入文件, 然后使用FileStream对象读取数据。The following example writes data to a file and then reads the data using the FileStream object.

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();
        }
    }
}

Imports System
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") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

使用此FileStream构造函数可在文件创建时应用访问权限。Use this FileStream constructor to apply access rights at the point of creation of a file. 若要在现有文件上访问或修改权限, 请考虑GetAccessControl使用SetAccessControl和方法。To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.

参数用于提供对在FileStream创建对象时可以利用的更高级操作的访问。 fileOptionsThe fileOptions parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

rights
FileSystemRights FileSystemRights FileSystemRights FileSystemRights

一个常数,确定为文件创建访问和审核规则时要使用的访问权。A constant that determines the access rights to use when creating access and audit rules for the file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

options
FileOptions FileOptions FileOptions FileOptions

一个指定附加文件选项的常数。A constant that specifies additional file options.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

bufferSize 为负数或零。bufferSize is negative or zero.

-or- modeaccessshare 包含无效的值。mode, access, or share contain an invalid value.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

当前操作系统不是 Windows NT 或更高版本。The current operating system is not Windows NT or later.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

- 或 --or- Encrypted 指定用于 options,但在当前平台上不支持文件加密。Encrypted is specified for options, but file encryption is not supported on the current platform.

指定的 path、文件名或这两者都超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

注解

.NET Framework 不支持通过作为设备名称的路径 (例如 "\\.\PHYSICALDRIVE0") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

使用此FileStream构造函数可在文件创建时应用访问权限。Use this FileStream constructor to apply access rights at the point of creation of a file. 若要在现有文件上访问或修改权限, 请考虑GetAccessControl使用SetAccessControl和方法。To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.

参数用于提供对在FileStream创建对象时可以利用的更高级操作的访问。 fileOptionsThe fileOptions parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于确定 FileStream 对象访问文件的方式。A constant that determines how the file can be accessed by the FileStream object. 该常数还可以确定由 FileStream 对象的 CanReadCanWrite 属性返回的值。This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. 如果 path 指定磁盘文件,则 CanSeektrueCanSeek is true if path specifies a disk file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

useAsync
Boolean Boolean Boolean Boolean

指定使用异步 I/O 还是同步 I/O。Specifies whether to use asynchronous I/O or synchronous I/O. 但是,请注意,基础操作系统可能不支持异步 I/O,因此在指定 true 后,根据所用平台,句柄可能同步打开。However, note that the underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be opened synchronously depending on the platform. 当异步打开时,BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 方法在执行大量读或写时效果更好,但对于少量的读/写,这些方法速度可能要慢得多。When opened asynchronously, the BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) and BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) methods perform better on large reads or writes, but they might be much slower for small reads or writes. 如果应用程序打算利用异步 I/O,将 useAsync 参数设置为 trueIf the application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. 正确使用异步 I/O 可以使应用程序的速度加快 10 倍,但是如果在没有为异步 I/O 重新设计应用程序的情况下使用异步 I/O,则可能使性能降低 10 倍。Using asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

bufferSize 为负数或零。bufferSize is negative or zero.

-or- modeaccessshare 包含无效的值。mode, access, or share contain an invalid value.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 系统正在运行 Windows 98 或 Windows 98 Second Edition,并将 share 设置为 FileShare.DeleteThe system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

示例

下面的代码示例演示如何以异步方式将数据写入文件, 然后验证是否已正确写入数据。The following code example shows how to asynchronously write data to a file and then verify that the data was written correctly. 创建State一个对象, 用于将信息从主线程传递EndReadCallback到和EndWriteCallback方法。A State object is created to pass information from the main thread to the EndReadCallback and EndWriteCallback methods.

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; } }
    }
}
Imports System
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") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于确定 FileStream 对象访问文件的方式。A constant that determines how the file can be accessed by the FileStream object. 该常数还可以确定由 FileStream 对象的 CanReadCanWrite 属性返回的值。This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. 如果 path 指定磁盘文件,则 CanSeektrueCanSeek is true if path specifies a disk file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

bufferSize 为负数或零。bufferSize is negative or zero.

-or- modeaccessshare 包含无效的值。mode, access, or share contain an invalid value.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 系统正在运行 Windows 98 或 Windows 98 Second Edition,并将 share 设置为 FileShare.DeleteThe system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

注解

.NET Framework 不支持通过作为设备名称的路径 (例如 "\\.\PHYSICALDRIVE0") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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

警告

此 API 现已过时。

使用指定的读/写权限、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.

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
[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")]
[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);
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 IntPtr IntPtr IntPtr

FileStream 对象将封装的文件的文件句柄。A file handle for the file that this FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean Boolean Boolean Boolean

如果文件句柄将由此 FileStream 实例所有,则为 true;否则为 falsetrue if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

isAsync
Boolean Boolean Boolean Boolean

如果异步打开句柄(即以重叠的 I/O 模式),则为 true;否则为 falsetrue if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false.

异常

access 小于 FileAccess.Read 或大于 FileAccess.ReadWrite,或者 bufferSize 小于等于 0。access is less than FileAccess.Read or greater than FileAccess.ReadWrite or bufferSize is less than or equal to 0.

该句柄无效。The handle is invalid.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

-or-

已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

FileStream对象提供对文件的指定访问权限。The FileStream object is given the specified access to the file. 句柄的所有权将为指定的。The ownership of the handle will be as specified. 如果这FileStream拥有句柄, 则对Close方法的调用也将关闭句柄。If this FileStream owns the handle, a call to the Close method will also close the handle. 特别是, 文件的句柄计数递减。In particular, the file's handle count is decremented. FileStream对象提供指定的缓冲区大小。The FileStream object is given the specified buffer size.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. 或者, 在调用此FileStream构造函数之前, 读取并写入句柄。Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

SecurityPermission
用于访问非托管代码。for access to unmanaged code. 关联的枚举UnmanagedCode:。Associated enumeration: UnmanagedCode.

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于确定 FileStream 对象访问文件的方式。A constant that determines how the file can be accessed by the FileStream object. 该常数还可以确定由 FileStream 对象的 CanReadCanWrite 属性返回的值。This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. 如果 path 指定磁盘文件,则 CanSeektrueCanSeek is true if path specifies a disk file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 系统正在运行 Windows 98 或 Windows 98 Second Edition,并将 share 设置为 FileShare.DeleteThe system is running Windows 98 or Windows 98 Second Edition and share is set to FileShare.Delete.

- 或 --or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

示例

此代码示例是为Lock方法提供的一个更大示例的一部分。This code example is part of a larger example provided for the Lock method.

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))
Dim aFileStream As New FileStream( _
    "Test#@@#.dat", FileMode.OpenOrCreate, _
    FileAccess.ReadWrite, FileShare.ReadWrite)

注解

.NET Framework 不支持通过作为设备名称的路径 (例如 "\\.\PHYSICALDRIVE0") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

构造函数对文件具有读/写访问权限, 并且该构造函数已打开共享读取访问权限 (也就是说, 此对象或其他进程打开文件以进行写入的请求将失败, FileStream直到该对象关闭, 否则读取尝试将会成功)。The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). 缓冲区大小设置为默认大小 (4096 字节) (4 KB)。The buffer size is set to the default size of 4096 bytes (4 KB).

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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)

使用指定的路径、创建模式、读/写和共享权限、其他 FileStreams 可以具有的对此文件的访问权限、缓冲区大小和附加文件选项初始化 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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于确定 FileStream 对象访问文件的方式。A constant that determines how the file can be accessed by the FileStream object. 该常数还可以确定由 FileStream 对象的 CanReadCanWrite 属性返回的值。This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. 如果 path 指定磁盘文件,则 CanSeektrueCanSeek is true if path specifies a disk file.

share
FileShare FileShare FileShare FileShare

一个常数,确定文件将如何由进程共享。A constant that determines how the file will be shared by processes.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

options
FileOptions FileOptions FileOptions FileOptions

一个指定附加文件选项的值。A value that specifies additional file options.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

bufferSize 为负数或零。bufferSize is negative or zero.

-or- modeaccessshare 包含无效的值。mode, access, or share contain an invalid value.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

-or- Encrypted 指定用于 options,但在当前平台上不支持文件加密。Encrypted is specified for options, but file encryption is not supported on the current platform.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

示例

下面的示例将数据写入文件, 然后使用FileStream对象读取数据。The following example writes data to a file and then reads the data using the FileStream object.

#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();
        }
    }
}

Imports System
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") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

参数用于提供对在FileStream创建对象时可以利用的更高级操作的访问。 fileOptionsThe fileOptions parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 SafeFileHandle SafeFileHandle SafeFileHandle

FileStream 对象将封装的文件的文件句柄。A file handle for the file that this FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

isAsync
Boolean Boolean Boolean Boolean

如果异步打开句柄(即以重叠的 I/O 模式),则为 true;否则为 falsetrue if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false.

异常

handle 参数是无效的句柄。The handle parameter is an invalid handle.

- 或 --or- handle 参数是同步句柄,但被异步使用。The handle parameter is a synchronous handle and it was used asynchronously.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

-or-

已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

isAsync参数设置为true , 以异步打开文件句柄。You set the isAsync parameter to true to open the file handle asynchronously. 当参数为true时, 流将使用重叠的 i/o 以异步方式执行文件操作。When the parameter is true, the stream utilizes overlapped I/O to perform file operations asynchronously. true但参数无需ReadAsync调用、 WriteAsyncCopyToAsync方法。However, the parameter does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. 当参数为false , 并且您调用异步读写操作时, UI 线程仍不会被阻止, 但实际的 i/o 操作将以同步方式执行。 isAsyncWhen the isAsync parameter 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.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. 或者, 在调用此FileStream构造函数之前, 读取并写入句柄。Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

SecurityPermission
用于调用非托管代码的权限。for permission to call unmanaged code. 关联的枚举:UnmanagedCodeAssociated enumerations: UnmanagedCode

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于确定 FileStream 对象访问文件的方式。A constant that determines how the file can be accessed by the FileStream object. 该常数还可以确定由 FileStream 对象的 CanReadCanWrite 属性返回的值。This also determines the values returned by the CanRead and CanWrite properties of the FileStream object. 如果 path 指定磁盘文件,则 CanSeektrueCanSeek is true if path specifies a disk file.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

-or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

对于指定的 path,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件或目录设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified path, such as when access is Write or ReadWrite and the file or directory is set for read-only access.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

注解

.NET Framework 不支持通过作为设备名称的路径 (例如 "\\.\PHYSICALDRIVE0") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

构造函数对文件具有读/写访问权限, 并且该构造函数已打开共享读取访问权限 (也就是说, 此对象或其他进程打开文件以进行写入的请求将失败, FileStream直到该对象关闭, 否则读取尝试将会成功)。The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed). 缓冲区大小设置为默认大小 (4096 字节) (4 KB)。The buffer size is set to the default size of 4096 bytes (4 KB).

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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

警告

此 API 现已过时。

使用指定的读/写权限和 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.

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle);
[System.Obsolete("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
[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")]
[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);
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 IntPtr IntPtr IntPtr

当前 FileStream 对象将封装的文件的文件句柄。A file handle for the file that the current FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean Boolean Boolean Boolean

如果文件句柄将由此 FileStream 实例所有,则为 true;否则为 falsetrue if the file handle will be owned by this FileStream instance; otherwise, false.

异常

access 不是 FileAccess 的字段。access is not a field of FileAccess.

调用方没有所要求的权限。The caller does not have the required permission.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

- 或 --or-

已关闭流。The stream has been closed.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

FileStream对象提供对文件的指定访问权限。The FileStream object is given the specified access to the file. 句柄的所有权将为指定的。The ownership of the handle will be as specified. 如果此进程拥有该句柄, 则对Close方法的调用还将关闭句柄, 并减少文件的句柄计数。If this process owns the handle, a call to the Close method will also close the handle and the file's handle count is decremented. FileStream对象指定默认缓冲区大小 (4096 字节)。The FileStream object is given the default buffer size of 4096 bytes.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用句柄之前调用, 并避免在Close使用句柄完成后调用以外的方法。For data safety, call Flush before using the handle, and avoid calling methods other than Close after you are done using the handle.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 SafeFileHandle SafeFileHandle SafeFileHandle

当前 FileStream 对象将封装的文件的文件句柄。A file handle for the file that the current FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个 FileAccess 常数,它设置 FileStream 对象的 CanReadCanWrite 属性。A FileAccess constant that sets the CanRead and CanWrite properties of the FileStream object.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

异常

handle 参数是无效的句柄。The handle parameter is an invalid handle.

- 或 --or- handle 参数是同步句柄,但被异步使用。The handle parameter is a synchronous handle and it was used asynchronously.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

-or-

已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. 或者, 在调用此FileStream构造函数之前, 读取并写入句柄。Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

SecurityPermission
用于调用非托管代码的权限。for permission to call unmanaged code. 关联的枚举:UnmanagedCodeAssociated enumerations: UnmanagedCode

另请参阅

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

警告

此 API 现已过时。

使用指定的读/写权限、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.

public:
 FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
[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")]
[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);
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 IntPtr IntPtr IntPtr

FileStream 对象将封装的文件的文件句柄。A file handle for the file that this FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

ownsHandle
Boolean Boolean Boolean Boolean

如果文件句柄将由此 FileStream 实例所有,则为 true;否则为 falsetrue if the file handle will be owned by this FileStream instance; otherwise, false.

bufferSize
Int32 Int32 Int32 Int32

一个大于零的正 Int32 值,表示缓冲区大小。A positive Int32 value greater than 0 indicating the buffer size. 默认缓冲区大小为 4096。The default buffer size is 4096.

异常

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

-or-

已关闭流。The stream has been closed.

调用方没有所要求的权限。The caller does not have the required permission.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

FileStream对象提供对文件的指定访问权限。The FileStream object is given the specified access to the file. 句柄的所有权将为指定的。The ownership of the handle will be as specified. 如果这FileStream拥有句柄, 则对Close方法的调用也将关闭句柄。If this FileStream owns the handle, a call to the Close method will also close the handle. 特别是, 文件的句柄计数递减。In particular, the file's handle count is decremented. FileStream对象提供指定的缓冲区大小。The FileStream object is given the specified buffer size.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. 或者, 在调用此FileStream构造函数之前, 读取并写入句柄。Alternately, read and write to the handle before calling this FileStream constructor.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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.

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 String String String

当前 FileStream 对象将封装的文件的相对路径或绝对路径。A relative or absolute path for the file that the current FileStream object will encapsulate.

mode
FileMode FileMode FileMode FileMode

一个确定如何打开或创建文件的常数。A constant that determines how to open or create the file.

异常

path 是一个空字符串 (""),仅包含空格,或者包含一个或多个无效字符。path is an empty string (""), contains only white space, or contains one or more invalid characters.

- 或 --or- path 指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.

path 指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。path refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.

调用方没有所要求的权限。The caller does not have the required permission.

找不到该文件。例如,当 modeFileMode.TruncateFileMode.Open,并且 path 指定的文件不存在时会出现这种情况。The file cannot be found, such as when mode is FileMode.Truncate or FileMode.Open, and the file specified by path does not exist. 该文件必须以这些模式存在。The file must already exist in these modes.

path 指定只读文件。path specifies a file that is read-only.

I/O 错误,例如在 path 指定的文件已存在时指定 FileMode.CreateNew,会发生此错误。An I/O error, such as specifying FileMode.CreateNew when the file specified by path already exists, occurred.

-or- 已关闭流。The stream has been closed.

指定的路径无效,例如位于未映射的驱动器上。The specified path is invalid, such as being on an unmapped drive.

指定的路径和/或文件名超过了系统定义的最大长度。The specified path, file name, or both exceed the system-defined maximum length.

示例

下面的代码示例演示了如何按字节将数据写入文件, 然后验证是否已正确写入数据。The following code example shows how to write data to a file, byte by byte, and then verify that the data was written correctly.

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);
        }
    }
}
Imports Microsoft.VisualBasic
Imports System
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") 直接访问物理磁盘。The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".

path参数可以是文件名, 包括通用命名约定 (UNC) 共享上的文件。The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.

构造函数对文件具有读/写访问权限, 并且该构造函数已打开共享读取访问权限 (也就是说, 此对象或其他进程打开文件以进行写入的请求将失败, FileStream直到该对象关闭, 否则读取尝试将会成功)。The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed).

不能使用此构造函数打开只读文件;相反, 必须使用接受FileAccess值设置为FileAccess.Read的参数的构造函数。You cannot use this constructor to open read-only files; instead, you must use a constructor that accepts a FileAccess parameter with the value set to FileAccess.Read.

缓冲区大小设置为默认大小 (4096 字节) (4 KB)。The buffer size is set to the default size of 4096 bytes (4 KB).

备注

path不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。path is not required to be a file stored on disk; it can be any part of a system that supports access through streams. 例如, 根据系统, 此类可以访问物理设备。For example, depending on the system, this class can access a physical device.

CanSeek适用于封装FileStream文件的所有对象。 trueCanSeek is true for all FileStream objects that encapsulate files. 如果path指示不支持查找的设备, 则上FileStreamCanSeek属性将为falseIf path indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false. 有关附加信息,请参见 CanSeekFor additional information, see CanSeek.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

对于没有FileAccess参数的构造函数, mode如果参数设置为Append, Write则是默认访问。For constructors without a FileAccess parameter, if the mode parameter is set to Append, Write is the default access. 否则, 访问将设置为ReadWriteOtherwise, the access is set to ReadWrite.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

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

警告

此 API 现已过时。

使用指定的读/写权限为指定的文件句柄初始化 FileStream 类的新实例。Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

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

参数

handle
IntPtr IntPtr IntPtr IntPtr

当前 FileStream 对象将封装的文件的文件句柄。A file handle for the file that the current FileStream object will encapsulate.

access
FileAccess FileAccess FileAccess FileAccess

一个常数,用于设置 FileStream 对象的 CanReadCanWrite 属性。A constant that sets the CanRead and CanWrite properties of the FileStream object.

异常

access 不是 FileAccess 的字段。access is not a field of FileAccess.

调用方没有所要求的权限。The caller does not have the required permission.

出现 I/O 错误,例如磁盘错误。An I/O error, such as a disk error, occurred.

- 或 --or-

已关闭流。The stream has been closed.

对于指定的文件句柄,操作系统不允许所请求的 access。例如当 accessWriteReadWrite,并将文件句柄设置为只读访问时会出现此情况。The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.

注解

调用Close时, 句柄也会关闭, 并且文件的句柄计数将减少。When Close is called, the handle is also closed and the file's handle count is decremented.

FileStream假定它对句柄具有独占控制。FileStream assumes that it has exclusive control over the handle. 同时读取、写入或查找时FileStream , 同时也持有句柄可能会导致数据损坏。Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. 为实现数据安全, Flush请在使用该句柄之前调用, 并避免在Close使用完句柄之后调用其他任何方法。For data safety, call Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle.

注意

使用特定的区域性设置编译一组字符并使用不同的区域性设置检索这些相同的字符时, 这些字符可能不是可解释, 并且可能会导致引发异常。When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.

FileShare.ReadFileStreamFileShare带参数的构造函数的默认值。FileShare.Read is the default for those FileStream constructors without a FileShare parameter.

有关常见文件和目录操作的列表, 请参阅常见 I/o 任务For a list of common file and directory operations, see Common I/O Tasks.

安全性

FileIOPermission
用于读取、写入和追加到文件。for reading, writing, and appending to files. 关联的枚举Read: Write、和AppendAssociated enumerations: Read, Write, and Append.

另请参阅

适用于