FileStream 构造函数
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
初始化 FileStream 类的新实例。
重载
FileStream(SafeFileHandle, FileAccess)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的读/写权限为指定的文件句柄初始化 FileStream 类的新实例。
public:
FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess)
参数
- handle
- SafeFileHandle
当前 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
例外
access
不是 FileAccess 的字段。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
调用 时 Close ,句柄也会关闭,并且文件的句柄计数会递减。
FileStream
假定它具有对句柄的独占控制。 读取 FileStream
、写入或查找同时持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免调用除使用句柄之后以外的 Close
任何方法。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)
使用指定的路径、创建模式、访问权限和共享权限、缓冲区大小、附加文件选项、访问控制和审核安全初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::Security::AccessControl::FileSystemRights rights, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options, System::Security::AccessControl::FileSecurity ^ fileSecurity);
public FileStream (string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity);
new System.IO.FileStream : string * System.IO.FileMode * System.Security.AccessControl.FileSystemRights * System.IO.FileShare * int * System.IO.FileOptions * System.Security.AccessControl.FileSecurity -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, rights As FileSystemRights, share As FileShare, bufferSize As Integer, options As FileOptions, fileSecurity As FileSecurity)
参数
- path
- String
当前 FileStream 对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- rights
- FileSystemRights
枚举值的按位组合,它用于确定在为文件创建访问和审核规则时要使用的访问权限。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
- options
- FileOptions
枚举值的按位组合,它用于指定其他文件选项。
- fileSecurity
- FileSecurity
一个对象,用于确定文件的访问控制和审核安全性。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
或
Encrypted 指定用于 options
,但在当前平台上不支持文件加密。
指定的 path
、文件名或这两者都超过了系统定义的最大长度。
当前操作系统不是 Windows NT 或更高版本。
示例
以下示例将数据写入文件,然后使用 对象读取数据 FileStream 。
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Security::AccessControl;
using namespace System::Security::Principal;
int main()
{
try
{
// Create a file and write data to it.
// Create an array of bytes.
array<Byte>^ messageByte =
Encoding::ASCII->GetBytes("Here is some data.");
// Specify an access control list (ACL)
FileSecurity^ fs = gcnew FileSecurity();
fs->AddAccessRule(
gcnew FileSystemAccessRule("MYDOMAIN\\MyAccount",
FileSystemRights::Modify, AccessControlType::Allow));
// Create a file using the FileStream class.
FileStream^ fWrite = gcnew FileStream("test.txt",
FileMode::Create, FileSystemRights::Modify,
FileShare::None, 8, FileOptions::None, fs);
// Write the number of bytes to the file.
fWrite->WriteByte((Byte)messageByte->Length);
// Write the bytes to the file.
fWrite->Write(messageByte, 0, messageByte->Length);
// Close the stream.
fWrite->Close();
// Open a file and read the number of bytes.
FileStream^ fRead =
gcnew FileStream("test.txt", FileMode::Open);
// The first byte is the string length.
int length = (int)fRead->ReadByte();
// Create a new byte array for the data.
array<Byte>^ readBytes = gcnew array<Byte>(length);
// Read the data from the file.
fRead->Read(readBytes, 0, readBytes->Length);
// Close the stream.
fRead->Close();
// Display the data.
Console::WriteLine(Encoding::ASCII->GetString(readBytes));
Console::WriteLine("Done writing and reading data.");
}
catch (IdentityNotMappedException^)
{
Console::WriteLine("You need to use your own credentials " +
" 'MYDOMAIN\\MyAccount'.");
}
catch (IOException^ ex)
{
Console::WriteLine(ex->Message);
}
}
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;
namespace FileSystemExample
{
class FileStreamExample
{
public static void Main()
{
try
{
// Create a file and write data to it.
// Create an array of bytes.
byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");
// Specify an access control list (ACL)
FileSecurity fs = new FileSecurity();
fs.AddAccessRule(new FileSystemAccessRule(@"DOMAINNAME\AccountName",
FileSystemRights.ReadData,
AccessControlType.Allow));
// Create a file using the FileStream class.
FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs);
// Write the number of bytes to the file.
fWrite.WriteByte((byte)messageByte.Length);
// Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length);
// Close the stream.
fWrite.Close();
// Open a file and read the number of bytes.
FileStream fRead = new FileStream("test.txt", FileMode.Open);
// The first byte is the string length.
int length = (int)fRead.ReadByte();
// Create a new byte array for the data.
byte[] readBytes = new byte[length];
// Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length);
// Close the stream.
fRead.Close();
// Display the data.
Console.WriteLine(Encoding.ASCII.GetString(readBytes));
Console.WriteLine("Done writing and reading data.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
open System
open System.IO;
open System.Text
open System.Security.AccessControl;
try
// Create a file and write data to it.
// Create an array of bytes.
let messageByte = Encoding.ASCII.GetBytes "Here is some data."
// Specify an access control list (ACL)
let fs = FileSecurity()
FileSystemAccessRule(@"DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow)
|> fs.AddAccessRule
// Create a file using the FileStream class.
let fWrite = new FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs)
// Write the number of bytes to the file.
byte messageByte.Length
|> fWrite.WriteByte
// Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length);
// Close the stream.
fWrite.Close();
// Open a file and read the number of bytes.
let fRead = new FileStream("test.txt", FileMode.Open)
// The first byte is the string length.
let length = fRead.ReadByte() |> int
// Create a new byte array for the data.
let readBytes = Array.zeroCreate length
// Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length);
// Close the stream.
fRead.Close();
// Display the data.
printfn $"{Encoding.ASCII.GetString readBytes}"
printfn "Done writing and reading data."
with e ->
printfn $"{e}"
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Module FileStreamExample
Sub Main()
Try
' Create a file and write data to it.
' Create an array of bytes.
Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.")
' Specify an access control list (ACL)
Dim fs As New FileSecurity()
fs.AddAccessRule(New FileSystemAccessRule("DOMAINNAME\AccountName", FileSystemRights.ReadData, AccessControlType.Allow))
' Create a file using the FileStream class.
Dim fWrite As New FileStream("test.txt", FileMode.Create, FileSystemRights.Modify, FileShare.None, 8, FileOptions.None, fs)
' Write the number of bytes to the file.
fWrite.WriteByte(System.Convert.ToByte(messageByte.Length))
' Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length)
' Close the stream.
fWrite.Close()
' Open a file and read the number of bytes.
Dim fRead As New FileStream("test.txt", FileMode.Open)
' The first byte is the string length.
Dim length As Integer = Fix(fRead.ReadByte())
' Create a new byte array for the data.
Dim readBytes(length) As Byte
' Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length)
' Close the stream.
fRead.Close()
' Display the data.
Console.WriteLine(Encoding.ASCII.GetString(readBytes))
Console.WriteLine("Done writing and reading data.")
Catch e As Exception
Console.WriteLine(e)
End Try
Console.ReadLine()
End Sub
End Module
注解
.NET Framework不支持通过设备名称路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
使用此 FileStream 构造函数在创建文件时应用访问权限。 若要访问或修改现有文件的权限,请考虑使用 GetAccessControl 和 SetAccessControl 方法。
参数 fileOptions
用于提供对创建 FileStream 对象时可以利用的更高级操作的访问。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统,此类可以访问物理设备。
CanSeek 对于 true
封装文件的所有 FileStream 对象。 如果 path
指示设备不支持查找,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
重要
.NET Core 中不存在此构造函数。 相反,从 .NET Core 3.1 开始,可以在程序集内使用以下 类的FileSystemAclExtensions
System.Security.AccessControl
扩展方法:Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)。
另请参阅
适用于
FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)
使用指定的路径、创建模式、访问权限和共享权限、缓冲区大小和附加文件选项初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::Security::AccessControl::FileSystemRights rights, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options);
public FileStream (string path, System.IO.FileMode mode, System.Security.AccessControl.FileSystemRights rights, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);
new System.IO.FileStream : string * System.IO.FileMode * System.Security.AccessControl.FileSystemRights * System.IO.FileShare * int * System.IO.FileOptions -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, rights As FileSystemRights, share As FileShare, bufferSize As Integer, options As FileOptions)
参数
- path
- String
当前 FileStream 对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- rights
- FileSystemRights
枚举值的按位组合,它用于确定在为文件创建访问和审核规则时要使用的访问权限。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
- options
- FileOptions
枚举值的按位组合,它用于指定其他文件选项。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
当前操作系统不是 Windows NT 或更高版本。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
或
Encrypted 指定用于 options
,但在当前平台上不支持文件加密。
指定的 path
、文件名或这两者都超过了系统定义的最大长度。
注解
.NET Framework不支持通过设备名称路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
使用此 FileStream 构造函数在创建文件时应用访问权限。 若要访问或修改现有文件的权限,请考虑使用 GetAccessControl 和 SetAccessControl 方法。
参数 fileOptions
用于提供对创建 FileStream 对象时可以利用的更高级操作的访问。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统,此类可以访问物理设备。
CanSeek 对于 true
封装文件的所有 FileStream 对象。 如果 path
指示设备不支持查找,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径、创建模式、读/写和共享权限、其他 FileStreams 可以具有的对此文件的访问权限、缓冲区大小和附加文件选项初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize, System::IO::FileOptions options);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int * System.IO.FileOptions -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer, options As FileOptions)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- access
- FileAccess
枚举值的按位组合,这些枚举值确定 FileStream
对象访问文件的方式。 该常数还可以确定由 FileStream
对象的 CanRead 和 CanWrite 属性返回的值。 如果 path
指定磁盘文件,则 CanSeek 为 true
。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
- options
- FileOptions
枚举值的按位组合,它用于指定其他文件选项。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
或
Encrypted 指定用于 options
,但在当前平台上不支持文件加密。
指定的路径和/或文件名超过了系统定义的最大长度。
示例
以下示例将数据写入文件,然后使用 对象读取数据 FileStream 。
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Security::AccessControl;
int main()
{
try
{
// Create a file and write data to it.
// Create an array of bytes.
array<Byte>^ messageByte =
Encoding::ASCII->GetBytes("Here is some data.");
// Create a file using the FileStream class.
FileStream^ fWrite = gcnew FileStream("test.txt", FileMode::Create,
FileAccess::ReadWrite, FileShare::None, 8, FileOptions::None);
// Write the number of bytes to the file.
fWrite->WriteByte((Byte)messageByte->Length);
// Write the bytes to the file.
fWrite->Write(messageByte, 0, messageByte->Length);
// Close the stream.
fWrite->Close();
// Open a file and read the number of bytes.
FileStream^ fRead = gcnew FileStream("test.txt",
FileMode::Open);
// The first byte is the string length.
int length = (int)fRead->ReadByte();
// Create a new byte array for the data.
array<Byte>^ readBytes = gcnew array<Byte>(length);
// Read the data from the file.
fRead->Read(readBytes, 0, readBytes->Length);
// Close the stream.
fRead->Close();
// Display the data.
Console::WriteLine(Encoding::ASCII->GetString(readBytes));
Console::WriteLine("Done writing and reading data.");
}
catch (IOException^ ex)
{
Console::WriteLine(ex->Message);
}
}
using System;
using System.IO;
using System.Text;
using System.Security.AccessControl;
namespace FileSystemExample
{
class FileStreamExample
{
public static void Main()
{
try
{
// Create a file and write data to it.
// Create an array of bytes.
byte[] messageByte = Encoding.ASCII.GetBytes("Here is some data.");
// Create a file using the FileStream class.
FileStream fWrite = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None);
// Write the number of bytes to the file.
fWrite.WriteByte((byte)messageByte.Length);
// Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length);
// Close the stream.
fWrite.Close();
// Open a file and read the number of bytes.
FileStream fRead = new FileStream("test.txt", FileMode.Open);
// The first byte is the string length.
int length = (int)fRead.ReadByte();
// Create a new byte array for the data.
byte[] readBytes = new byte[length];
// Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length);
// Close the stream.
fRead.Close();
// Display the data.
Console.WriteLine(Encoding.ASCII.GetString(readBytes));
Console.WriteLine("Done writing and reading data.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
}
open System.IO
open System.Text
try
// Create a file and write data to it.
// Create an array of bytes.
let messageByte = Encoding.ASCII.GetBytes "Here is some data."
// Create a file using the FileStream class.
let fWrite =
new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None)
// Write the number of bytes to the file.
byte messageByte.Length |> fWrite.WriteByte
// Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length)
// Close the stream.
fWrite.Close()
// Open a file and read the number of bytes.
let fRead = new FileStream("test.txt", FileMode.Open)
// The first byte is the string length.
let length = fRead.ReadByte() |> int
// Create a new byte array for the data.
let readBytes = Array.zeroCreate length
// Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length) |> ignore
// Close the stream.
fRead.Close()
// Display the data.
printfn $"{Encoding.ASCII.GetString readBytes}"
printfn "Done writing and reading data."
with e ->
printfn $"{e}"
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Module FileStreamExample
Sub Main()
Try
' Create a file and write data to it.
' Create an array of bytes.
Dim messageByte As Byte() = Encoding.ASCII.GetBytes("Here is some data.")
' Create a file using the FileStream class.
Dim fWrite As New FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 8, FileOptions.None)
' Write the number of bytes to the file.
fWrite.WriteByte(System.Convert.ToByte(messageByte.Length))
' Write the bytes to the file.
fWrite.Write(messageByte, 0, messageByte.Length)
' Close the stream.
fWrite.Close()
' Open a file and read the number of bytes.
Dim fRead As New FileStream("test.txt", FileMode.Open)
' The first byte is the string length.
Dim length As Integer = Fix(fRead.ReadByte())
' Create a new byte array for the data.
Dim readBytes(length) As Byte
' Read the data from the file.
fRead.Read(readBytes, 0, readBytes.Length)
' Close the stream.
fRead.Close()
' Display the data.
Console.WriteLine(Encoding.ASCII.GetString(readBytes))
Console.WriteLine("Done writing and reading data.")
Catch e As Exception
Console.WriteLine(e)
End Try
Console.ReadLine()
End Sub
End Module
注解
.NET Framework不支持通过设备名称路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 fileOptions
用于提供对创建 FileStream 对象时可以利用的更高级操作的访问。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统,此类可以访问物理设备。
CanSeek 对于 true
封装文件的所有 FileStream 对象。 如果 path
指示设备不支持查找,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileAccess, FileShare, Int32)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
用指定的路径、创建模式、读/写及共享权限和缓冲区大小初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- access
- FileAccess
枚举值的按位组合,这些枚举值确定 FileStream
对象访问文件的方式。 该常数还可以确定由 FileStream
对象的 CanRead 和 CanWrite 属性返回的值。 如果 path
指定磁盘文件,则 CanSeek 为 true
。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
指定的路径和/或文件名超过了系统定义的最大长度。
注解
.NET Framework不支持通过设备名称路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统,此类可以访问物理设备。
CanSeek 对于 true
封装文件的所有 FileStream 对象。 如果 path
指示设备不支持查找,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202
注意
This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202
使用指定的读/写权限、FileStream 实例所属权、缓冲区大小和同步或异步状态为指定的文件句柄初始化 FileStream
类的新实例。
public:
FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize, bool isAsync);
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int * bool -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean, bufferSize As Integer, isAsync As Boolean)
参数
- handle
-
IntPtr
nativeint
此 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
- ownsHandle
- Boolean
如果文件句柄将由此 FileStream
实例所有,则为 true
;否则为 false
。
- isAsync
- Boolean
如果异步打开句柄(即以重叠的 I/O 模式),则为 true
;否则为 false
。
- 属性
例外
access
小于 FileAccess.Read
或大于 FileAccess.ReadWrite
,或者 bufferSize
小于等于 0。
该句柄无效。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
向 FileStream
对象授予对文件的指定访问权限。 句柄的所有权将按指定。 如果它 FileStream
拥有句柄,则对 方法的 Close 调用也将关闭句柄。 具体而言,文件的句柄计数会递减。 为 FileStream
对象提供指定的缓冲区大小。
FileStream
假定它具有对句柄的独占控制。 读取 FileStream
、写入或查找同时持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免调用除使用句柄之后以外的 Close
任何方法。 或者,在调用此 FileStream
构造函数之前,对句柄进行读取和写入。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileAccess, FileShare)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径、创建模式、读/写权限和共享权限创建 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- access
- FileAccess
枚举值的按位组合,这些枚举值确定 FileStream
对象访问文件的方式。 该常数还可以确定由 FileStream
对象的 CanRead 和 CanWrite 属性返回的值。 如果 path
指定磁盘文件,则 CanSeek 为 true
。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
指定的路径和/或文件名超过了系统定义的最大长度。
mode
包含无效值。
示例
此代码示例是为 方法提供的更大示例的 Lock 一部分。
FileStream^ fileStream = gcnew FileStream( "Test#@@#.dat",FileMode::OpenOrCreate,FileAccess::ReadWrite,FileShare::ReadWrite );
using(FileStream fileStream = new FileStream(
"Test#@@#.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.ReadWrite))
use fileStream =
new FileStream("Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim aFileStream As New FileStream( _
"Test#@@#.dat", FileMode.OpenOrCreate, _
FileAccess.ReadWrite, FileShare.ReadWrite)
注解
.NET Framework不支持通过设备名称路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
向构造函数授予对该文件的读/写访问权限,并且打开它共享读取访问权限 (也就是说,打开由此进程或其他进程写入的文件的请求将失败,直到 FileStream
对象已关闭,但读取尝试) 成功。 缓冲区大小设置为默认大小 4096 字节 (4 KB) 。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统,此类可以访问物理设备。
CanSeek 对于 true
封装文件的所有 FileStream 对象。 如果 path
指示设备不支持查找,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(IntPtr, FileAccess, Boolean, Int32)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202
注意
This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202
使用指定的读/写权限、FileStream 实例所属权和缓冲区大小为指定的文件句柄初始化 FileStream
类的新实例。
public:
FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle, int bufferSize);
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool * int -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean, bufferSize As Integer)
参数
- handle
-
IntPtr
nativeint
此 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
- ownsHandle
- Boolean
如果文件句柄将由此 FileStream
实例所有,则为 true
;否则为 false
。
- 属性
例外
bufferSize
为负数。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
向 FileStream
对象授予对文件的指定访问权限。 句柄的所有权将按指定。 如果此 FileStream
拥有句柄,则对 方法的 Close 调用也将关闭句柄。 具体而言,文件的句柄计数会递减。 为 FileStream
对象指定了指定的缓冲区大小。
FileStream
假定它具有对句柄的独占控制。 读取、写入或查找同时 FileStream
持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免在完成使用句柄后调用任何其他 Close
方法。 或者,在调用此 FileStream
构造函数之前读取和写入句柄。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径、创建模式、读/写和共享权限、缓冲区大小和同步或异步状态初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share, int bufferSize, bool useAsync);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, bool useAsync);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare * int * bool -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess, share As FileShare, bufferSize As Integer, useAsync As Boolean)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- access
- FileAccess
枚举值的按位组合,这些枚举值确定 FileStream
对象访问文件的方式。 该常数还可以确定由 FileStream
对象的 CanRead 和 CanWrite 属性返回的值。 如果 path
指定磁盘文件,则 CanSeek 为 true
。
- share
- FileShare
枚举值的按位组合,这些枚举值确定进程共享文件的方式。
- useAsync
- Boolean
指定使用异步 I/O 还是同步 I/O。 但是,请注意,基础操作系统可能不支持异步 I/O,因此在指定 true
后,根据所用平台,句柄可能同步打开。 当异步打开时,BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 和 BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 方法在执行大量读或写时效果更好,但对于少量的读/写,这些方法速度可能要慢得多。 如果应用程序打算利用异步 I/O,将 useAsync
参数设置为 true
。 正确使用异步 I/O 可以使应用程序的速度加快 10 倍,但是如果在没有为异步 I/O 重新设计应用程序的情况下使用异步 I/O,则可能使性能降低 10 倍。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
指定的路径和/或文件名超过了系统定义的最大长度。
示例
下面的代码示例演示如何以异步方式将数据写入文件,然后验证数据是否正确写入。 创建一个 State
对象,用于将信息从main线程传递到 EndReadCallback
和 EndWriteCallback
方法。
using namespace System;
using namespace System::IO;
using namespace System::Threading;
// Maintain state information to be passed to
// EndWriteCallback and EndReadCallback.
ref class State
{
private:
// fStream is used to read and write to the file.
FileStream^ fStream;
// writeArray stores data that is written to the file.
array<Byte>^writeArray;
// readArray stores data that is read from the file.
array<Byte>^readArray;
// manualEvent signals the main thread
// when verification is complete.
ManualResetEvent^ manualEvent;
public:
State( FileStream^ fStream, array<Byte>^writeArray, ManualResetEvent^ manualEvent )
{
this->fStream = fStream;
this->writeArray = writeArray;
this->manualEvent = manualEvent;
readArray = gcnew array<Byte>(writeArray->Length);
}
property FileStream^ FStream
{
FileStream^ get()
{
return fStream;
}
}
property array<Byte>^ WriteArray
{
array<Byte>^ get()
{
return writeArray;
}
}
property array<Byte>^ ReadArray
{
array<Byte>^ get()
{
return readArray;
}
}
property ManualResetEvent^ ManualEvent
{
ManualResetEvent^ get()
{
return manualEvent;
}
}
};
ref class FStream
{
private:
// When BeginRead is finished reading data from the file, the
// EndReadCallback method is called to end the asynchronous
// read operation and then verify the data.
static void EndReadCallback( IAsyncResult^ asyncResult )
{
State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState);
int readCount = tempState->FStream->EndRead( asyncResult );
int i = 0;
while ( i < readCount )
{
if ( tempState->ReadArray[ i ] != tempState->WriteArray[ i++ ] )
{
Console::WriteLine( "Error writing data." );
tempState->FStream->Close();
return;
}
}
Console::WriteLine( "The data was written to {0} "
"and verified.", tempState->FStream->Name );
tempState->FStream->Close();
// Signal the main thread that the verification is finished.
tempState->ManualEvent->Set();
}
public:
// When BeginWrite is finished writing data to the file, the
// EndWriteCallback method is called to end the asynchronous
// write operation and then read back and verify the data.
static void EndWriteCallback( IAsyncResult^ asyncResult )
{
State^ tempState = dynamic_cast<State^>(asyncResult->AsyncState);
FileStream^ fStream = tempState->FStream;
fStream->EndWrite( asyncResult );
// Asynchronously read back the written data.
fStream->Position = 0;
asyncResult = fStream->BeginRead( tempState->ReadArray, 0, tempState->ReadArray->Length, gcnew AsyncCallback( &FStream::EndReadCallback ), tempState );
// Concurrently do other work, such as
// logging the write operation.
}
};
int main()
{
// Create a synchronization object that gets
// signaled when verification is complete.
ManualResetEvent^ manualEvent = gcnew ManualResetEvent( false );
// Create the data to write to the file.
array<Byte>^writeArray = gcnew array<Byte>(100000);
(gcnew Random)->NextBytes( writeArray );
FileStream^ fStream = gcnew FileStream( "Test#@@#.dat",FileMode::Create,FileAccess::ReadWrite,FileShare::None,4096,true );
// Check that the FileStream was opened asynchronously.
Console::WriteLine( "fStream was {0}opened asynchronously.", fStream->IsAsync ? (String^)"" : "not " );
// Asynchronously write to the file.
IAsyncResult^ asyncResult = fStream->BeginWrite( writeArray, 0, writeArray->Length, gcnew AsyncCallback( &FStream::EndWriteCallback ), gcnew State( fStream,writeArray,manualEvent ) );
// Concurrently do other work and then wait
// for the data to be written and verified.
manualEvent->WaitOne( 5000, false );
}
using System;
using System.IO;
using System.Threading;
class FStream
{
static void Main()
{
// Create a synchronization object that gets
// signaled when verification is complete.
ManualResetEvent manualEvent = new ManualResetEvent(false);
// Create random data to write to the file.
byte[] writeArray = new byte[100000];
new Random().NextBytes(writeArray);
FileStream fStream =
new FileStream("Test#@@#.dat", FileMode.Create,
FileAccess.ReadWrite, FileShare.None, 4096, true);
// Check that the FileStream was opened asynchronously.
Console.WriteLine("fStream was {0}opened asynchronously.",
fStream.IsAsync ? "" : "not ");
// Asynchronously write to the file.
IAsyncResult asyncResult = fStream.BeginWrite(
writeArray, 0, writeArray.Length,
new AsyncCallback(EndWriteCallback),
new State(fStream, writeArray, manualEvent));
// Concurrently do other work and then wait
// for the data to be written and verified.
manualEvent.WaitOne(5000, false);
}
// When BeginWrite is finished writing data to the file, the
// EndWriteCallback method is called to end the asynchronous
// write operation and then read back and verify the data.
static void EndWriteCallback(IAsyncResult asyncResult)
{
State tempState = (State)asyncResult.AsyncState;
FileStream fStream = tempState.FStream;
fStream.EndWrite(asyncResult);
// Asynchronously read back the written data.
fStream.Position = 0;
asyncResult = fStream.BeginRead(
tempState.ReadArray, 0 , tempState.ReadArray.Length,
new AsyncCallback(EndReadCallback), tempState);
// Concurrently do other work, such as
// logging the write operation.
}
// When BeginRead is finished reading data from the file, the
// EndReadCallback method is called to end the asynchronous
// read operation and then verify the data.
static void EndReadCallback(IAsyncResult asyncResult)
{
State tempState = (State)asyncResult.AsyncState;
int readCount = tempState.FStream.EndRead(asyncResult);
int i = 0;
while(i < readCount)
{
if(tempState.ReadArray[i] != tempState.WriteArray[i++])
{
Console.WriteLine("Error writing data.");
tempState.FStream.Close();
return;
}
}
Console.WriteLine("The data was written to {0} and verified.",
tempState.FStream.Name);
tempState.FStream.Close();
// Signal the main thread that the verification is finished.
tempState.ManualEvent.Set();
}
// Maintain state information to be passed to
// EndWriteCallback and EndReadCallback.
class State
{
// fStream is used to read and write to the file.
FileStream fStream;
// writeArray stores data that is written to the file.
byte[] writeArray;
// readArray stores data that is read from the file.
byte[] readArray;
// manualEvent signals the main thread
// when verification is complete.
ManualResetEvent manualEvent;
public State(FileStream fStream, byte[] writeArray,
ManualResetEvent manualEvent)
{
this.fStream = fStream;
this.writeArray = writeArray;
this.manualEvent = manualEvent;
readArray = new byte[writeArray.Length];
}
public FileStream FStream
{ get{ return fStream; } }
public byte[] WriteArray
{ get{ return writeArray; } }
public byte[] ReadArray
{ get{ return readArray; } }
public ManualResetEvent ManualEvent
{ get{ return manualEvent; } }
}
}
open System
open System.IO
open System.Threading
// Maintain state information to be passed to
// EndWriteCallback and EndReadCallback.
type State(fStream: FileStream, writeArray: byte[], manualEvent: ManualResetEvent) =
// readArray stores data that is read from the file.
let readArray = Array.zeroCreate writeArray.Length
member _.FStream = fStream
member _.WriteArray = writeArray
member _.ReadArray = readArray
member _.ManualEvent = manualEvent
// When BeginRead is finished reading data from the file, the
// EndReadCallback method is called to end the asynchronous
// read operation and then verify the data.
let endReadCallback (asyncResult: IAsyncResult) =
let tempState = asyncResult.AsyncState :?> State
let readCount = tempState.FStream.EndRead asyncResult
let mutable i = 0
let mutable errored = false
while i < readCount do
if tempState.ReadArray[i] <> tempState.WriteArray[i] then
printfn "Error writing data."
tempState.FStream.Close()
errored <- true
i <- readCount
i <- i + 1
printfn $"The data was written to {tempState.FStream.Name} and verified."
tempState.FStream.Close()
// Signal the main thread that the verification is finished.
tempState.ManualEvent.Set() |> ignore
// When BeginWrite is finished writing data to the file, the
// EndWriteCallback method is called to end the asynchronous
// write operation and then read back and verify the data.
let endWriteCallback (asyncResult: IAsyncResult) =
let tempState = asyncResult.AsyncState :?> State
let fStream = tempState.FStream
fStream.EndWrite asyncResult
// Asynchronously read back the written data.
fStream.Position <- 0
let asyncResult =
fStream.BeginRead(tempState.ReadArray, 0, tempState.ReadArray.Length, AsyncCallback endReadCallback, tempState)
// Concurrently do other work, such as
// logging the write operation.
()
// Create a synchronization object that gets
// signaled when verification is complete.
let manualEvent = new ManualResetEvent false
// Create random data to write to the file.
let writeArray = Array.zeroCreate 100000
Random.Shared.NextBytes writeArray
let fStream =
new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true)
// Check that the FileStream was opened asynchronously.
if fStream.IsAsync then "" else "not "
|> printfn "fStream was %sopened asynchronously."
// Asynchronously write to the file.
let asyncResult =
fStream.BeginWrite(
writeArray,
0,
writeArray.Length,
AsyncCallback endWriteCallback,
State(fStream, writeArray, manualEvent)
)
// Concurrently do other work and then wait
// for the data to be written and verified.
manualEvent.WaitOne(5000, false) |> ignore
Imports System.IO
Imports System.Threading
Class FStream
Shared Sub Main()
' Create a synchronization object that gets
' signaled when verification is complete.
Dim manualEvent As New ManualResetEvent(False)
' Create random data to write to the file.
Dim writeArray(100000) As Byte
Dim randomGenerator As New Random()
randomGenerator.NextBytes(writeArray)
Dim fStream As New FileStream("Test#@@#.dat", _
FileMode.Create, FileAccess.ReadWrite, _
FileShare.None, 4096, True)
' Check that the FileStream was opened asynchronously.
If fStream.IsAsync = True
Console.WriteLine("fStream was opened asynchronously.")
Else
Console.WriteLine("fStream was not opened asynchronously.")
End If
' Asynchronously write to the file.
Dim asyncResult As IAsyncResult = fStream.BeginWrite( _
writeArray, 0, writeArray.Length, _
AddressOf EndWriteCallback , _
New State(fStream, writeArray, manualEvent))
' Concurrently do other work and then wait
' for the data to be written and verified.
manualEvent.WaitOne(5000, False)
End Sub
' When BeginWrite is finished writing data to the file, the
' EndWriteCallback method is called to end the asynchronous
' write operation and then read back and verify the data.
Private Shared Sub EndWriteCallback(asyncResult As IAsyncResult)
Dim tempState As State = _
DirectCast(asyncResult.AsyncState, State)
Dim fStream As FileStream = tempState.FStream
fStream.EndWrite(asyncResult)
' Asynchronously read back the written data.
fStream.Position = 0
asyncResult = fStream.BeginRead( _
tempState.ReadArray, 0 , tempState.ReadArray.Length, _
AddressOf EndReadCallback, tempState)
' Concurrently do other work, such as
' logging the write operation.
End Sub
' When BeginRead is finished reading data from the file, the
' EndReadCallback method is called to end the asynchronous
' read operation and then verify the data.
Private Shared Sub EndReadCallback(asyncResult As IAsyncResult)
Dim tempState As State = _
DirectCast(asyncResult.AsyncState, State)
Dim readCount As Integer = _
tempState.FStream.EndRead(asyncResult)
Dim i As Integer = 0
While(i < readCount)
If(tempState.ReadArray(i) <> tempState.WriteArray(i))
Console.WriteLine("Error writing data.")
tempState.FStream.Close()
Return
End If
i += 1
End While
Console.WriteLine("The data was written to {0} and " & _
"verified.", tempState.FStream.Name)
tempState.FStream.Close()
' Signal the main thread that the verification is finished.
tempState.ManualEvent.Set()
End Sub
' Maintain state information to be passed to
' EndWriteCallback and EndReadCallback.
Private Class State
' fStreamValue is used to read and write to the file.
Dim fStreamValue As FileStream
' writeArrayValue stores data that is written to the file.
Dim writeArrayValue As Byte()
' readArrayValue stores data that is read from the file.
Dim readArrayValue As Byte()
' manualEvent signals the main thread
' when verification is complete.
Dim manualEventValue As ManualResetEvent
Sub New(aStream As FileStream, anArray As Byte(), _
manualEvent As ManualResetEvent)
fStreamValue = aStream
writeArrayValue = anArray
manualEventValue = manualEvent
readArrayValue = New Byte(anArray.Length - 1){}
End Sub
Public ReadOnly Property FStream() As FileStream
Get
Return fStreamValue
End Get
End Property
Public ReadOnly Property WriteArray() As Byte()
Get
Return writeArrayValue
End Get
End Property
Public ReadOnly Property ReadArray() As Byte()
Get
Return readArrayValue
End Get
End Property
Public ReadOnly Property ManualEvent() As ManualResetEvent
Get
Return manualEventValue
End Get
End Property
End Class
End Class
注解
.NET Framework不支持通过作为设备名称的路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统的不同,此类可以访问物理设备。
CanSeek 用于 true
封装文件的所有 FileStream 对象。 如果 path
指示不支持查找的设备,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileMode, FileAccess)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径、创建模式和读/写权限初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access);
public FileStream (string path, System.IO.FileMode mode, System.IO.FileAccess access);
new System.IO.FileStream : string * System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode, access As FileAccess)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
- access
- FileAccess
枚举值的按位组合,这些枚举值确定 FileStream
对象访问文件的方式。 该常数还可以确定由 FileStream
对象的 CanRead 和 CanWrite 属性返回的值。 如果 path
指定磁盘文件,则 CanSeek 为 true
。
例外
path
为 null
。
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
对于指定的 path
,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件或目录设置为只读访问时会出现此情况。
指定的路径和/或文件名超过了系统定义的最大长度。
mode
包含无效值。
注解
.NET Framework不支持通过作为设备名称的路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
向构造函数授予对文件的读/写访问权限,并且打开它共享读取访问权限 (也就是说,打开此进程或其他进程写入的文件的请求将失败,直到 FileStream
对象关闭,但读取尝试) 成功。 缓冲区大小设置为默认大小 4096 字节 (4 KB) 。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统的不同,此类可以访问物理设备。
CanSeek 用于 true
封装文件的所有 FileStream 对象。 如果 path
指示不支持查找的设备,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(IntPtr, FileAccess, Boolean)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202
注意
This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202
使用指定的读/写权限和 FileStream 实例所属权为指定的文件句柄初始化 FileStream
类的新实例。
public:
FileStream(IntPtr handle, System::IO::FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) and optionally make a new SafeFileHandle with ownsHandle=false if needed instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean)
参数
- handle
-
IntPtr
nativeint
当前 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
- ownsHandle
- Boolean
如果文件句柄将由此 FileStream
实例所有,则为 true
;否则为 false
。
- 属性
例外
access
不是 FileAccess 的字段。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
向 FileStream
对象授予对文件的指定访问权限。 句柄的所有权将按指定。 如果此进程拥有句柄,则对 方法的 Close 调用也将关闭句柄,并且文件的句柄计数将递减。 对象 FileStream
的默认缓冲区大小为 4096 字节。
FileStream
假定它具有对句柄的独占控制。 读取、写入或查找同时 FileStream
持有句柄可能会导致数据损坏。 为保护数据安全,请在使用句柄之前调用 Flush ,避免在使用句柄后调用 Close
其他方法。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(SafeFileHandle, FileAccess, Int32)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的读/写权限和缓冲区大小为指定的文件句柄初始化 FileStream 类的新实例。
public:
FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access, int bufferSize);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess * int -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess, bufferSize As Integer)
参数
- handle
- SafeFileHandle
当前 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
一个 FileAccess 常数,它设置 FileStream
对象的 CanRead 和 CanWrite 属性。
例外
bufferSize
参数为负。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
FileStream
假定它具有对句柄的独占控制。 读取、写入或查找同时 FileStream
持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免在完成使用句柄后调用任何其他 Close
方法。 或者,在调用此 FileStream
构造函数之前读取和写入句柄。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(SafeFileHandle, FileAccess, Int32, Boolean)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的读/写权限、缓冲区大小和同步或异步状态为指定的文件句柄初始化 FileStream 类的新实例。
public:
FileStream(Microsoft::Win32::SafeHandles::SafeFileHandle ^ handle, System::IO::FileAccess access, int bufferSize, bool isAsync);
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access, int bufferSize, bool isAsync);
new System.IO.FileStream : Microsoft.Win32.SafeHandles.SafeFileHandle * System.IO.FileAccess * int * bool -> System.IO.FileStream
Public Sub New (handle As SafeFileHandle, access As FileAccess, bufferSize As Integer, isAsync As Boolean)
参数
- handle
- SafeFileHandle
此 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
- isAsync
- Boolean
如果异步打开句柄(即以重叠的 I/O 模式),则为 true
;否则为 false
。
例外
bufferSize
参数为负。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
将 参数true
设置为 isAsync
以异步方式打开文件句柄。 当 参数为 true
时,流利用重叠的 I/O 以异步方式执行文件操作。 但是, 参数不必是 true
来调用 ReadAsync、 WriteAsync或 CopyToAsync 方法。 isAsync
当 参数为 false
并且调用异步读取和写入操作时,UI 线程仍不会被阻止,但实际 I/O 操作会同步执行。
FileStream
假定它具有对句柄的独占控制。 读取、写入或查找同时 FileStream
持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免在完成使用句柄后调用任何其他 Close
方法。 或者,在调用此 FileStream
构造函数之前读取和写入句柄。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(String, FileStreamOptions)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径、创建模式、读/写和共享权限、缓冲区大小、其他文件选项、预分配大小以及其他 FileStreams 对同一文件的访问权限初始化 类的新实例 FileStream 。
public:
FileStream(System::String ^ path, System::IO::FileStreamOptions ^ options);
public FileStream (string path, System.IO.FileStreamOptions options);
new System.IO.FileStream : string * System.IO.FileStreamOptions -> System.IO.FileStream
Public Sub New (path As String, options As FileStreamOptions)
参数
- path
- String
当前 FileStream 实例将封装的文件的相对路径或绝对路径。
- options
- FileStreamOptions
描述要使用的可选 FileStream 参数的 对象。
例外
path
或 options
为 null
。
path
指非 NTFS 环境中的非文件设备,如 CON:
、COM1:
LPT1:
、 等。
找不到该文件。例如,当 Mode 是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
I/O 错误,例如在 path
指定的文件已存在时指定 FileMode.CreateNew
,会发生此错误。
或
已关闭流。
-或-
磁盘在提供 时 PreallocationSize (已满,并且 path
指向常规文件) 。
-或-
文件在提供 时 PreallocationSize (太大,并且 path
指向常规文件) 。
调用方没有所要求的权限。
指定的路径无效,例如位于未映射的驱动器上。
指定的路径和/或文件名超过了系统定义的最大长度。
注解
为 指定值 PreallocationSize 可提供有关预分配大小的提示,但不提供强有力的保证。 有关完整用法的详细信息,请参阅 的文档 PreallocationSize。
适用于
FileStream(String, FileMode)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
使用指定的路径和创建模式初始化 FileStream 类的新实例。
public:
FileStream(System::String ^ path, System::IO::FileMode mode);
public FileStream (string path, System.IO.FileMode mode);
new System.IO.FileStream : string * System.IO.FileMode -> System.IO.FileStream
Public Sub New (path As String, mode As FileMode)
参数
- path
- String
当前 FileStream
对象将封装的文件的相对路径或绝对路径。
- mode
- FileMode
用于确定文件的打开或创建方式的枚举值之一。
例外
.NET Framework和 .NET Core 版本早于 2.1:path
是空字符串 (“”) ,仅包含空格,或包含一个或多个无效字符。
或
path
指非文件设备,如 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
指非文件设备,如非 NTFS 环境中的“con:”、“com1:”、“lpt1:”等。
path
为 null
。
调用方没有所要求的权限。
找不到该文件。例如,当 mode
是 FileMode.Truncate
或 FileMode.Open
,并且 path
指定的文件不存在时会出现这种情况。 该文件必须以这些模式存在。
path
指定只读文件。
指定的路径无效,例如位于未映射的驱动器上。
指定的路径和/或文件名超过了系统定义的最大长度。
mode
包含无效值。
示例
下面的代码示例演示如何按字节将数据写入文件,然后验证数据是否正确写入。
using namespace System;
using namespace System::IO;
int main()
{
String^ fileName = "Test@##@.dat";
// Create random data to write to the file.
array<Byte>^dataArray = gcnew array<Byte>(100000);
(gcnew Random)->NextBytes( dataArray );
FileStream^ fileStream = gcnew FileStream( fileName,FileMode::Create );
try
{
// Write the data to the file, byte by byte.
for ( int i = 0; i < dataArray->Length; i++ )
{
fileStream->WriteByte( dataArray[ i ] );
}
// Set the stream position to the beginning of the file.
fileStream->Seek( 0, SeekOrigin::Begin );
// Read and verify the data.
for ( int i = 0; i < fileStream->Length; i++ )
{
if ( dataArray[ i ] != fileStream->ReadByte() )
{
Console::WriteLine( "Error writing data." );
return -1;
}
}
Console::WriteLine( "The data was written to {0} "
"and verified.", fileStream->Name );
}
finally
{
fileStream->Close();
}
}
using System;
using System.IO;
class FStream
{
static void Main()
{
const string fileName = "Test#@@#.dat";
// Create random data to write to the file.
byte[] dataArray = new byte[100000];
new Random().NextBytes(dataArray);
using(FileStream
fileStream = new FileStream(fileName, FileMode.Create))
{
// Write the data to the file, byte by byte.
for(int i = 0; i < dataArray.Length; i++)
{
fileStream.WriteByte(dataArray[i]);
}
// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin);
// Read and verify the data.
for(int i = 0; i < fileStream.Length; i++)
{
if(dataArray[i] != fileStream.ReadByte())
{
Console.WriteLine("Error writing data.");
return;
}
}
Console.WriteLine("The data was written to {0} " +
"and verified.", fileStream.Name);
}
}
}
open System
open System.IO
let fileName = "Test#@@#.dat"
// Create random data to write to the file.
let dataArray = Array.zeroCreate 100000
Random.Shared.NextBytes dataArray
do
use fileStream = new FileStream(fileName, FileMode.Create)
// Write the data to the file, byte by byte.
for i = 0 to dataArray.Length - 1 do
fileStream.WriteByte dataArray[i]
// Set the stream position to the beginning of the file.
fileStream.Seek(0, SeekOrigin.Begin) |> ignore
// Read and verify the data.
for i in 0L .. fileStream.Length - 1L do
if dataArray[int i] <> (fileStream.ReadByte() |> byte) then
printfn "Error writing data."
exit 1
printfn $"The data was written to {fileStream.Name} and verified."
Imports System.IO
Imports System.Text
Class FStream
Shared Sub Main()
Const fileName As String = "Test#@@#.dat"
' Create random data to write to the file.
Dim dataArray(100000) As Byte
Dim randomGenerator As New Random()
randomGenerator.NextBytes(dataArray)
Dim fileStream As FileStream = _
new FileStream(fileName, FileMode.Create)
Try
' Write the data to the file, byte by byte.
For i As Integer = 0 To dataArray.Length - 1
fileStream.WriteByte(dataArray(i))
Next i
' Set the stream position to the beginning of the stream.
fileStream.Seek(0, SeekOrigin.Begin)
' Read and verify the data.
For i As Integer = 0 To _
CType(fileStream.Length, Integer) - 1
If dataArray(i) <> fileStream.ReadByte() Then
Console.WriteLine("Error writing data.")
Return
End If
Next i
Console.WriteLine("The data was written to {0} " & _
"and verified.", fileStream.Name)
Finally
fileStream.Close()
End Try
End Sub
End Class
注解
.NET Framework不支持通过作为设备名称的路径(如“\\.\PHYSICALDRIVE0”)直接访问物理磁盘。
参数 path
可以是文件名,包括通用命名约定 (UNC) 共享上的文件。
向构造函数授予对文件的读/写访问权限,并且打开它共享读取访问权限 (也就是说,打开此进程或其他进程写入的文件的请求将失败,直到 FileStream
对象关闭,但读取尝试) 成功。
不能使用此构造函数打开只读文件;相反,必须使用接受 FileAccess
参数的构造函数,其值设置为 FileAccess.Read
。
缓冲区大小设置为默认大小 4096 字节 (4 KB) 。
注意
path
不需要是存储在磁盘上的文件;它可以是支持通过流进行访问的系统的任何部分。 例如,根据系统的不同,此类可以访问物理设备。
CanSeek 用于 true
封装文件的所有 FileStream 对象。 如果 path
指示不支持查找的设备,则 CanSeek 生成的 FileStream 上的 属性为 false
。 有关附加信息,请参见 CanSeek。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
对于没有 参数的 FileAccess 构造函数,如果 参数 mode
设置为 Append, Write 则为默认访问。 否则,访问权限设置为 ReadWrite。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
FileStream(IntPtr, FileAccess)
- Source:
- FileStream.cs
- Source:
- FileStream.cs
- Source:
- FileStream.cs
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202
注意
This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.
注意
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202
使用指定的读/写权限为指定的文件句柄初始化 FileStream 类的新实例。
public:
FileStream(IntPtr handle, System::IO::FileAccess access);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
[System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
[System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
public FileStream (IntPtr handle, System.IO.FileAccess access);
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Use FileStream(SafeFileHandle handle, FileAccess access) instead.")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
[<System.Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess)
参数
- handle
-
IntPtr
nativeint
当前 FileStream
对象将封装的文件的文件句柄。
- access
- FileAccess
- 属性
例外
access
不是 FileAccess 的字段。
调用方没有所要求的权限。
对于指定的文件句柄,操作系统不允许所请求的 access
。例如当 access
是 Write
或 ReadWrite
,并将文件句柄设置为只读访问时会出现此情况。
注解
调用 时 Close ,句柄也会关闭,文件的句柄计数也会递减。
FileStream
假定它具有对句柄的独占控制。 读取、写入或查找同时 FileStream
持有句柄可能会导致数据损坏。 为了数据安全,请在使用句柄之前调用 Flush ,并避免在完成使用句柄后调用任何其他 Close
方法。
注意
编译具有特定区域性设置的一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
FileShare.Read
是那些 FileStream 没有 FileShare
参数的构造函数的默认值。
有关常见文件和目录操作的列表,请参阅 常见 I/O 任务。
另请参阅
适用于
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈