FileStream Konstruktory
Definicja
Inicjuje nowe wystąpienie klasy FileStream.Initializes a new instance of the FileStream class.
Przeciążenia
FileStream(SafeFileHandle, FileAccess) |
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, prawami dostępu i uprawnieniami do udostępniania, rozmiarem buforu, dodatkowymi opcjami plików, kontrolą dostępu i zabezpieczeniami inspekcji.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, prawami dostępu i uprawnieniem do udostępniania, rozmiarem buforu i dodatkowymi opcjami plików.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania, rozmiarem buforu i stanem synchronicznym lub asynchronicznym.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania oraz rozmiarem buforu.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) |
Nieaktualne.
Nieaktualne.
Nieaktualne.
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem odczyt/zapis, |
FileStream(String, FileMode, FileAccess, FileShare) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i uprawnieniami udostępniania.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania, dostęp innych FILESTREAM może mieć taki sam plik, rozmiar buforu i dodatkowe opcje plików.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) |
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku, z określonym uprawnieniem do odczytu/zapisu, rozmiarem buforu i stanem synchronicznym lub asynchronicznym.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) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia i uprawnieniem do odczytu/zapisu.Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission. |
FileStream(IntPtr, FileAccess, Boolean) |
Nieaktualne.
Nieaktualne.
Nieaktualne.
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu i |
FileStream(SafeFileHandle, FileAccess, Int32) |
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu i rozmiarem buforu.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) |
Nieaktualne.
Nieaktualne.
Nieaktualne.
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku, z określonym uprawnieniem do odczytu/zapisu, |
FileStream(String, FileMode) |
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką i trybem tworzenia.Initializes a new instance of the FileStream class with the specified path and creation mode. |
FileStream(IntPtr, FileAccess) |
Nieaktualne.
Nieaktualne.
Nieaktualne.
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu.Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission. |
FileStream(SafeFileHandle, FileAccess)
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu.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)
Parametry
- handle
- SafeFileHandle
Dojście do pliku, które FileStream
zostanie hermetyzowane przez bieżący obiekt.A file handle for the file that the current FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
Wyjątki
access
nie jest polem FileAccess .access
is not a field of FileAccess.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Gdy Close jest wywoływana, uchwyt jest również zamknięty, a Licznik dojść pliku jest zmniejszany.When Close is called, the handle is also closed and the file's handle count is decremented.
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, prawami dostępu i uprawnieniami do udostępniania, rozmiarem buforu, dodatkowymi opcjami plików, kontrolą dostępu i zabezpieczeniami inspekcji.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
Public Sub New (path As String, mode As FileMode, rights As FileSystemRights, share As FileShare, bufferSize As Integer, options As FileOptions, fileSecurity As FileSecurity)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- rights
- FileSystemRights
Bitowa kombinacja wartości wyliczenia, które określają prawa dostępu do użycia podczas tworzenia reguł dostępu i inspekcji dla pliku.A bitwise combination of the enumeration values that determines the access rights to use when creating access and audit rules for the file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- options
- FileOptions
Bitowa kombinacja wartości wyliczenia, które określają dodatkowe opcje plików.A bitwise combination of the enumeration values that specifies additional file options.
- fileSecurity
- FileSecurity
Obiekt, który określa kontrolę dostępu i zabezpieczenia inspekcji dla pliku.An object that determines the access control and audit security for the file.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
bufferSize
jest ujemna lub równa zero.bufferSize
is negative or zero.
-lub--or-
mode
, access
lub share
zawierają nieprawidłową wartość.mode
, access
, or share
contain an invalid value.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
-lub--or-
Encrypted jest określony dla options
, ale szyfrowanie plików nie jest obsługiwane na bieżącej platformie.Encrypted is specified for options
, but file encryption is not supported on the current platform.
Określona path
Nazwa pliku lub obie te wartości przekraczają maksymalną długość zdefiniowaną przez system.The specified path
, file name, or both exceed the system-defined maximum length.
Bieżący system operacyjny nie jest systemem Windows NT lub nowszym.The current operating system is not Windows NT or later.
Przykłady
Poniższy przykład zapisuje dane do pliku, a następnie odczytuje dane przy użyciu FileStream obiektu.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.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
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
Użyj tego FileStream konstruktora, aby zastosować prawa dostępu w momencie tworzenia pliku.Use this FileStream constructor to apply access rights at the point of creation of a file. Aby uzyskać dostęp do lub zmodyfikować prawa do istniejącego pliku, należy rozważyć GetAccessControl użycie SetAccessControl metod i.To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.
Ten fileOptions
parametr służy do zapewnienia dostępu do bardziej zaawansowanych operacji, których można użyć podczas tworzenia FileStream obiektu.The fileOptions
parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Ważne
Ten konstruktor nie istnieje w programie .NET Core.This constructor does not exist in .NET Core. Zamiast tego, począwszy od platformy .NET Core 3,1, można użyć następującej metody rozszerzenia FileSystemAclExtensions
klasy wewnątrz System.Security.AccessControl
zestawu: Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity) .Instead, starting in .NET Core 3.1, you can use the following extension method of the FileSystemAclExtensions
class inside the System.Security.AccessControl
assembly: Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity).
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, prawami dostępu i uprawnieniem do udostępniania, rozmiarem buforu i dodatkowymi opcjami plików.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- rights
- FileSystemRights
Bitowa kombinacja wartości wyliczenia, które określają prawa dostępu do użycia podczas tworzenia reguł dostępu i inspekcji dla pliku.A bitwise combination of the enumeration values that determines the access rights to use when creating access and audit rules for the file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- options
- FileOptions
Bitowa kombinacja wartości wyliczenia, które określają dodatkowe opcje plików.A bitwise combination of the enumeration values that specifies additional file options.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
bufferSize
jest ujemna lub równa zero.bufferSize
is negative or zero.
-lub--or-
mode
, access
lub share
zawierają nieprawidłową wartość.mode
, access
, or share
contain an invalid value.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Bieżący system operacyjny nie jest systemem Windows NT lub nowszym.The current operating system is not Windows NT or later.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
-lub--or-
Encrypted jest określony dla options
, ale szyfrowanie plików nie jest obsługiwane na bieżącej platformie.Encrypted is specified for options
, but file encryption is not supported on the current platform.
Określona path
Nazwa pliku lub obie te wartości przekraczają maksymalną długość zdefiniowaną przez system.The specified path
, file name, or both exceed the system-defined maximum length.
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
Użyj tego FileStream konstruktora, aby zastosować prawa dostępu w momencie tworzenia pliku.Use this FileStream constructor to apply access rights at the point of creation of a file. Aby uzyskać dostęp do lub zmodyfikować prawa do istniejącego pliku, należy rozważyć GetAccessControl użycie SetAccessControl metod i.To access or modify rights on an existing file, consider using the GetAccessControl and SetAccessControl methods.
Ten fileOptions
parametr służy do zapewnienia dostępu do bardziej zaawansowanych operacji, których można użyć podczas tworzenia FileStream obiektu.The fileOptions
parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania, rozmiarem buforu i stanem synchronicznym lub asynchronicznym.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która określa, w jaki sposób można uzyskać dostęp do pliku przez FileStream
obiekt.A bitwise combination of the enumeration values that determines how the file can be accessed by the FileStream
object. Określa również wartości zwracane przez CanRead CanWrite właściwości i FileStream
obiektu.This also determines the values returned by the CanRead and CanWrite properties of the FileStream
object. CanSeek jest true
Jeśli path
określa plik dysku.CanSeek is true
if path
specifies a disk file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- useAsync
- Boolean
Określa, czy ma być używane asynchroniczne operacje we/wy czy synchroniczne operacje we/wy.Specifies whether to use asynchronous I/O or synchronous I/O. Należy jednak pamiętać, że podstawowy system operacyjny może nie obsługiwać asynchronicznych operacji we/wy, więc true
w przypadku określenia, uchwyt może być otwarty synchronicznie w zależności od platformy.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. Po otwarciu asynchronicznej BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) metody i BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) działają lepiej przy dużych operacjach odczytu i zapisu, ale mogą one być znacznie wolniejsze w przypadku małych odczytów lub zapisów.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. Jeśli aplikacja została zaprojektowana tak, aby korzystała z asynchronicznej operacji we/wy, ustaw useAsync
parametr na true
.If the application is designed to take advantage of asynchronous I/O, set the useAsync
parameter to true
. Poprawne używanie operacji we/wy może przyspieszyć działanie aplikacji o ile nie jest to czynnik 10, ale bez konieczności ponownego projektowania aplikacji asynchronicznych operacji we/wy może zmniejszyć wydajność o tyle, ile wynosi 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.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
bufferSize
jest ujemna lub równa zero.bufferSize
is negative or zero.
-lub--or-
mode
, access
lub share
zawierają nieprawidłową wartość.mode
, access
, or share
contain an invalid value.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or-
System działa w systemie Windows 98 lub Windows 98 Second Edition i share
ma ustawioną wartość FileShare.Delete
.The system is running Windows 98 or Windows 98 Second Edition and share
is set to FileShare.Delete
.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
Przykłady
Poniższy przykład kodu pokazuje, jak asynchronicznie zapisywać dane do pliku, a następnie sprawdzać poprawność zapisu danych.The following code example shows how to asynchronously write data to a file and then verify that the data was written correctly. State
Obiekt jest tworzony w celu przekazywania informacji z wątku głównego do EndReadCallback
EndWriteCallback
metod i.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.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
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- File
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileAccess, FileShare, Int32)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania oraz rozmiarem buforu.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która określa, w jaki sposób można uzyskać dostęp do pliku przez FileStream
obiekt.A bitwise combination of the enumeration values that determines how the file can be accessed by the FileStream
object. Określa również wartości zwracane przez CanRead CanWrite właściwości i FileStream
obiektu.This also determines the values returned by the CanRead and CanWrite properties of the FileStream
object. CanSeek jest true
Jeśli path
określa plik dysku.CanSeek is true
if path
specifies a disk file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
bufferSize
jest ujemna lub równa zero.bufferSize
is negative or zero.
-lub--or-
mode
, access
lub share
zawierają nieprawidłową wartość.mode
, access
, or share
contain an invalid value.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or-
System działa w systemie Windows 98 lub Windows 98 Second Edition i share
ma ustawioną wartość FileShare.Delete
.The system is running Windows 98 or Windows 98 Second Edition and share
is set to FileShare.Delete
.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
Przestroga
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
Przestroga
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
Przestroga
Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem odczyt/zapis, FileStream
własność wystąpienia, rozmiar buforu i stan synchroniczny lub asynchroniczny.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);
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);
[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("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")]
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
[<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
[<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("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead")>]
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)
Parametry
- handle
- IntPtr
Dojście do pliku, które FileStream
będzie hermetyzowane przez ten obiekt.A file handle for the file that this FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
- ownsHandle
- Boolean
true
Jeśli dojście do pliku będzie własnością tego FileStream
wystąpienia; w przeciwnym razie, false
.true
if the file handle will be owned by this FileStream
instance; otherwise, false
.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- isAsync
- Boolean
true
Jeśli dojście zostało otwarte asynchronicznie (czyli w trybie we/wy); w przeciwnym razie false
.true
if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false
.
- Atrybuty
Wyjątki
access
jest mniejsza FileAccess.Read
lub FileAccess.ReadWrite
bufferSize
równa 0 lub mniejsza od zera.access
is less than FileAccess.Read
or greater than FileAccess.ReadWrite
or bufferSize
is less than or equal to 0.
Dojście jest nieprawidłowe.The handle is invalid.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Obiekt uzyskuje FileStream
określony dostęp do pliku.The FileStream
object is given the specified access to the file. Własność dojścia zostanie określona.The ownership of the handle will be as specified. Jeśli FileStream
jest to uchwyt, wywołanie Close metody również zamknie uchwytu.If this FileStream
owns the handle, a call to the Close method will also close the handle. W szczególności Licznik dojść pliku jest zmniejszany.In particular, the file's handle count is decremented. FileStream
Obiekt ma określony rozmiar buforu.The FileStream
object is given the specified buffer size.
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle. Alternatywnie Odczytaj i Zapisz do dojścia przed wywołaniem tego FileStream
konstruktora.Alternately, read and write to the handle before calling this FileStream
constructor.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileAccess, FileShare)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i uprawnieniami udostępniania.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która określa, w jaki sposób można uzyskać dostęp do pliku przez FileStream
obiekt.A bitwise combination of the enumeration values that determines how the file can be accessed by the FileStream
object. Określa również wartości zwracane przez CanRead CanWrite właściwości i FileStream
obiektu.This also determines the values returned by the CanRead and CanWrite properties of the FileStream
object. CanSeek jest true
Jeśli path
określa plik dysku.CanSeek is true
if path
specifies a disk file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or-
System działa w systemie Windows 98 lub Windows 98 Second Edition i share
ma ustawioną wartość FileShare.Delete
.The system is running Windows 98 or Windows 98 Second Edition and share
is set to FileShare.Delete
.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
mode
zawiera nieprawidłową wartość.mode
contains an invalid value.
Przykłady
Ten przykład kodu jest częścią większego przykładu dostarczonego dla Lock metody.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)
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Konstruktor uzyskuje dostęp do odczytu/zapisu do pliku i otwiera dostęp do odczytu (czyli żądania otwarcia pliku do zapisu przez ten lub inny proces zakończy się niepowodzeniem FileStream
, dopóki obiekt nie zostanie zamknięty, ale próby odczytu zakończą się pomyślnie).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). Rozmiar buforu jest ustawiony na domyślny rozmiar 4096 bajtów (4 KB).The buffer size is set to the default size of 4096 bytes (4 KB).
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia, uprawnieniem do odczytu/zapisu i udostępniania, dostęp innych FILESTREAM może mieć taki sam plik, rozmiar buforu i dodatkowe opcje plików.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która określa, w jaki sposób można uzyskać dostęp do pliku przez FileStream
obiekt.A bitwise combination of the enumeration values that determines how the file can be accessed by the FileStream
object. Określa również wartości zwracane przez CanRead CanWrite właściwości i FileStream
obiektu.This also determines the values returned by the CanRead and CanWrite properties of the FileStream
object. CanSeek jest true
Jeśli path
określa plik dysku.CanSeek is true
if path
specifies a disk file.
- share
- FileShare
Bitowa kombinacja wartości wyliczenia określająca sposób, w jaki plik będzie współużytkowany przez procesy.A bitwise combination of the enumeration values that determines how the file will be shared by processes.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- options
- FileOptions
Bitowa kombinacja wartości wyliczenia, które określają dodatkowe opcje plików.A bitwise combination of the enumeration values that specifies additional file options.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
bufferSize
jest ujemna lub równa zero.bufferSize
is negative or zero.
-lub--or-
mode
, access
lub share
zawierają nieprawidłową wartość.mode
, access
, or share
contain an invalid value.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
-lub--or-
Encrypted jest określony dla options
, ale szyfrowanie plików nie jest obsługiwane na bieżącej platformie.Encrypted is specified for options
, but file encryption is not supported on the current platform.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
Przykłady
Poniższy przykład zapisuje dane do pliku, a następnie odczytuje dane przy użyciu FileStream obiektu.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.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
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
Ten fileOptions
parametr służy do zapewnienia dostępu do bardziej zaawansowanych operacji, których można użyć podczas tworzenia FileStream obiektu.The fileOptions
parameter is used to provide access to more advanced operations that can be leveraged when creating a FileStream object.
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(SafeFileHandle, FileAccess, Int32, Boolean)
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku, z określonym uprawnieniem do odczytu/zapisu, rozmiarem buforu i stanem synchronicznym lub asynchronicznym.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)
Parametry
- handle
- SafeFileHandle
Dojście do pliku, które FileStream
będzie hermetyzowane przez ten obiekt.A file handle for the file that this FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- isAsync
- Boolean
true
Jeśli dojście zostało otwarte asynchronicznie (czyli w trybie we/wy); w przeciwnym razie false
.true
if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false
.
Wyjątki
handle
Parametr jest nieprawidłowym dojściem.The handle
parameter is an invalid handle.
-lub--or-
handle
Parametr jest dojściem synchronicznym i został użyty asynchronicznie.The handle
parameter is a synchronous handle and it was used asynchronously.
bufferSize
Parametr jest ujemny.The bufferSize
parameter is negative.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Ustaw parametr na, isAsync
true
Aby otworzyć dojście do pliku asynchronicznie.You set the isAsync
parameter to true
to open the file handle asynchronously. Gdy parametr ma wartość true
, strumień wykorzystuje nakładające się operacje we/wy na asynchroniczne wykonywanie operacji na plikach.When the parameter is true
, the stream utilizes overlapped I/O to perform file operations asynchronously. Jednak parametr nie musi być true
wywołaniem ReadAsync WriteAsync metody,, lub CopyToAsync .However, the parameter does not have to be true
to call the ReadAsync, WriteAsync, or CopyToAsync method. Gdy isAsync
parametr jest false
i wywołuje asynchroniczne operacje odczytu i zapisu, wątek interfejsu użytkownika nadal nie jest blokowany, ale rzeczywista operacja we/wy jest wykonywana synchronicznie.When 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
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle. Alternatywnie Odczytaj i Zapisz do dojścia przed wywołaniem tego FileStream
konstruktora.Alternately, read and write to the handle before calling this FileStream
constructor.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode, FileAccess)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką, trybem tworzenia i uprawnieniem do odczytu/zapisu.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która określa, w jaki sposób można uzyskać dostęp do pliku przez FileStream
obiekt.A bitwise combination of the enumeration values that determines how the file can be accessed by the FileStream
object. Określa również wartości zwracane przez CanRead CanWrite właściwości i FileStream
obiektu.This also determines the values returned by the CanRead and CanWrite properties of the FileStream
object. CanSeek jest true
Jeśli path
określa plik dysku.CanSeek is true
if path
specifies a disk file.
Wyjątki
path
to null
.path
is null
.
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or- Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
access
Żądany system operacyjny nie jest dozwolony dla danego elementu path
, na przykład gdy access
jest Write
lub ReadWrite
, a plik lub katalog jest ustawiony na dostęp tylko do odczytu.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.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
mode
zawiera nieprawidłową wartość.mode
contains an invalid value.
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Konstruktor uzyskuje dostęp do odczytu/zapisu do pliku i otwiera dostęp do odczytu (czyli żądania otwarcia pliku do zapisu przez ten lub inny proces zakończy się niepowodzeniem FileStream
, dopóki obiekt nie zostanie zamknięty, ale próby odczytu zakończą się pomyślnie).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). Rozmiar buforu jest ustawiony na domyślny rozmiar 4096 bajtów (4 KB).The buffer size is set to the default size of 4096 bytes (4 KB).
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(IntPtr, FileAccess, Boolean)
Przestroga
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
Przestroga
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
Przestroga
Use FileStream(SafeFileHandle handle, FileAccess access) instead
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu i FileStream
własnością wystąpienia.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);
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);
[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("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
public FileStream (IntPtr handle, System.IO.FileAccess access, bool ownsHandle);
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
[<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("Use FileStream(SafeFileHandle handle, FileAccess access) instead")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess * bool -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess, ownsHandle As Boolean)
Parametry
- handle
- IntPtr
Dojście do pliku, które FileStream
zostanie hermetyzowane przez bieżący obiekt.A file handle for the file that the current FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
- ownsHandle
- Boolean
true
Jeśli dojście do pliku będzie własnością tego FileStream
wystąpienia; w przeciwnym razie, false
.true
if the file handle will be owned by this FileStream
instance; otherwise, false
.
- Atrybuty
Wyjątki
access
nie jest polem FileAccess .access
is not a field of FileAccess.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Obiekt uzyskuje FileStream
określony dostęp do pliku.The FileStream
object is given the specified access to the file. Własność dojścia zostanie określona.The ownership of the handle will be as specified. Jeśli ten proces jest właścicielem dojścia, wywołanie Close metody również zamknie uchwytu, a liczba dojść pliku zostanie zmniejszona.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
Obiekt ma domyślny rozmiar buforu wynoszący 4096 bajtów.The FileStream
object is given the default buffer size of 4096 bytes.
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling methods other than Close
after you are done using the handle.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(SafeFileHandle, FileAccess, Int32)
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu i rozmiarem buforu.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)
Parametry
- handle
- SafeFileHandle
Dojście do pliku, które FileStream
zostanie hermetyzowane przez bieżący obiekt.A file handle for the file that the current FileStream
object will encapsulate.
- access
- FileAccess
FileAccessStała, która ustawia CanRead właściwości i CanWrite FileStream
obiektu.A FileAccess constant that sets the CanRead and CanWrite properties of the FileStream
object.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
Wyjątki
handle
Parametr jest nieprawidłowym dojściem.The handle
parameter is an invalid handle.
-lub--or-
handle
Parametr jest dojściem synchronicznym i został użyty asynchronicznie.The handle
parameter is a synchronous handle and it was used asynchronously.
bufferSize
Parametr jest ujemny.The bufferSize
parameter is negative.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle. Alternatywnie Odczytaj i Zapisz do dojścia przed wywołaniem tego FileStream
konstruktora.Alternately, read and write to the handle before calling this FileStream
constructor.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(IntPtr, FileAccess, Boolean, Int32)
Przestroga
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
Przestroga
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
Przestroga
Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku, z określonym uprawnieniem do odczytu/zapisu, FileStream
własnością wystąpienia i rozmiarem buforu.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);
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);
[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("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")]
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
[<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
[<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("Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead")>]
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)
Parametry
- handle
- IntPtr
Dojście do pliku, które FileStream
będzie hermetyzowane przez ten obiekt.A file handle for the file that this FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
- ownsHandle
- Boolean
true
Jeśli dojście do pliku będzie własnością tego FileStream
wystąpienia; w przeciwnym razie, false
.true
if the file handle will be owned by this FileStream
instance; otherwise, false
.
- bufferSize
- Int32
Wartość dodatnia Int32 większa niż 0 wskazuje rozmiar buforu.A positive Int32 value greater than 0 indicating the buffer size. Domyślny rozmiar buforu to 4096.The default buffer size is 4096.
- Atrybuty
Wyjątki
bufferSize
jest wartością ujemną.bufferSize
is negative.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Obiekt uzyskuje FileStream
określony dostęp do pliku.The FileStream
object is given the specified access to the file. Własność dojścia zostanie określona.The ownership of the handle will be as specified. Jeśli FileStream
jest to uchwyt, wywołanie Close metody również zamknie uchwytu.If this FileStream
owns the handle, a call to the Close method will also close the handle. W szczególności Licznik dojść pliku jest zmniejszany.In particular, the file's handle count is decremented. FileStream
Obiekt ma określony rozmiar buforu.The FileStream
object is given the specified buffer size.
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle. Alternatywnie Odczytaj i Zapisz do dojścia przed wywołaniem tego FileStream
konstruktora.Alternately, read and write to the handle before calling this FileStream
constructor.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(String, FileMode)
Inicjuje nowe wystąpienie FileStream klasy z określoną ścieżką i trybem tworzenia.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)
Parametry
- path
- String
Ścieżka względna lub bezwzględna dla pliku, który FileStream
będzie hermetyzowany bieżący obiekt.A relative or absolute path for the file that the current FileStream
object will encapsulate.
- mode
- FileMode
Jedna z wartości wyliczenia, która określa sposób otwierania lub tworzenia pliku.One of the enumeration values that determines how to open or create the file.
Wyjątki
path
jest pustym ciągiem (""), zawiera tylko znak odstępu lub zawiera jeden lub więcej nieprawidłowych znaków.path
is an empty string (""), contains only white space, or contains one or more invalid characters.
-lub--or-
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in an NTFS environment.
path
odnosi się do urządzenia niebędącego plikiem, takiego jak "con:", "COM1:", "LPT1:" itp. w środowisku innym niż NTFS.path
refers to a non-file device, such as "con:", "com1:", "lpt1:", etc. in a non-NTFS environment.
path
to null
.path
is null
.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Nie można znaleźć pliku, takiego jak when mode
FileMode.Truncate
lub FileMode.Open
, i plik określony przez path
nie istnieje.The file cannot be found, such as when mode
is FileMode.Truncate
or FileMode.Open
, and the file specified by path
does not exist. Plik musi już istnieć w tych trybach.The file must already exist in these modes.
path
Określa plik, który jest tylko do odczytu.path
specifies a file that is read-only.
Błąd we/wy, taki jak określenie FileMode.CreateNew
, kiedy plik określony przez path
już istnieje, wystąpił.An I/O error, such as specifying FileMode.CreateNew
when the file specified by path
already exists, occurred.
-lub--or- Strumień został zamknięty.The stream has been closed.
Określona ścieżka jest nieprawidłowa, na przykład na dysku niezamapowanym.The specified path is invalid, such as being on an unmapped drive.
Podana ścieżka, nazwa pliku lub obie przekraczają maksymalną długość zdefiniowaną przez system.The specified path, file name, or both exceed the system-defined maximum length.
mode
zawiera nieprawidłową wartość.mode
contains an invalid value.
Przykłady
Poniższy przykład kodu pokazuje, jak zapisywać dane do pliku, bajty przez bajty, a następnie sprawdzać poprawność zapisu danych.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 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
Uwagi
.NET Framework nie obsługuje bezpośredniego dostępu do dysków fizycznych za pomocą ścieżek, które są nazwami urządzeń, takimi jak " \ \ .\PHYSICALDRIVE0".The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0 ".
path
Parametr może być nazwą pliku, łącznie z plikiem w udziale Universal Naming Convention (UNC).The path
parameter can be a file name, including a file on a Universal Naming Convention (UNC) share.
Konstruktor uzyskuje dostęp do odczytu/zapisu do pliku i otwiera dostęp do odczytu (czyli żądania otwarcia pliku do zapisu przez ten lub inny proces zakończy się niepowodzeniem FileStream
, dopóki obiekt nie zostanie zamknięty, ale próby odczytu zakończą się pomyślnie).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).
Tego konstruktora nie można używać do otwierania plików tylko do odczytu; Zamiast tego należy użyć konstruktora, który akceptuje FileAccess
parametr z wartością ustawioną na 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
.
Rozmiar buforu jest ustawiony na domyślny rozmiar 4096 bajtów (4 KB).The buffer size is set to the default size of 4096 bytes (4 KB).
Uwaga
path
nie musi być plikiem przechowywanym na dysku; może to być dowolna część systemu, która obsługuje dostęp za pomocą strumieni.path
is not required to be a file stored on disk; it can be any part of a system that supports access through streams. Na przykład w zależności od systemu Ta klasa może uzyskać dostęp do urządzenia fizycznego.For example, depending on the system, this class can access a physical device.
CanSeek dotyczy true
wszystkich FileStream obiektów, które hermetyzują pliki.CanSeek is true
for all FileStream objects that encapsulate files. Jeśli path
wskazuje urządzenie, które nie obsługuje wyszukiwania, CanSeek Właściwość w wyniku FileStream ma wartość false
.If path
indicates a device that does not support seeking, the CanSeek property on the resulting FileStream is false
. Aby uzyskać dodatkowe informacje, zobacz CanSeek.For additional information, see CanSeek.
FileShare.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
W przypadku konstruktorów bez FileAccess parametru, jeśli mode
parametr jest ustawiony na Append , Write jest domyślnym dostępem.For constructors without a FileAccess parameter, if the mode
parameter is set to Append, Write is the default access. W przeciwnym razie dostęp jest ustawiany na ReadWrite .Otherwise, the access is set to ReadWrite.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- InvalidPathChars
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File
Dotyczy
FileStream(IntPtr, FileAccess)
Przestroga
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. http://go.microsoft.com/fwlink/?linkid=14202
Przestroga
This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202
Przestroga
Use FileStream(SafeFileHandle handle, FileAccess access) instead
Inicjuje nowe wystąpienie FileStream klasy dla określonego dojścia do pliku z określonym uprawnieniem do odczytu/zapisu.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);
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);
[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("Use FileStream(SafeFileHandle handle, FileAccess access) instead")]
public FileStream (IntPtr handle, System.IO.FileAccess access);
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
[<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("Use FileStream(SafeFileHandle handle, FileAccess access) instead")>]
new System.IO.FileStream : nativeint * System.IO.FileAccess -> System.IO.FileStream
Public Sub New (handle As IntPtr, access As FileAccess)
Parametry
- handle
- IntPtr
Dojście do pliku, które FileStream
zostanie hermetyzowane przez bieżący obiekt.A file handle for the file that the current FileStream
object will encapsulate.
- access
- FileAccess
Bitowa kombinacja wartości wyliczenia, która ustawia CanRead CanWrite właściwości i FileStream
obiektu.A bitwise combination of the enumeration values that sets the CanRead and CanWrite properties of the FileStream
object.
- Atrybuty
Wyjątki
access
nie jest polem FileAccess .access
is not a field of FileAccess.
Obiekt wywołujący nie posiada wymaganych uprawnień.The caller does not have the required permission.
Wystąpił błąd we/wy, taki jak błąd dysku.An I/O error, such as a disk error, occurred.
-lub--or-
Strumień został zamknięty.The stream has been closed.
access
Żądany plik nie jest dozwolony przez system operacyjny dla określonego dojścia do pliku, na przykład gdy access
jest Write
lub ReadWrite
, a dojście do pliku jest ustawione na dostęp tylko do odczytu.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.
Uwagi
Gdy Close jest wywoływana, uchwyt jest również zamknięty, a Licznik dojść pliku jest zmniejszany.When Close is called, the handle is also closed and the file's handle count is decremented.
FileStream
przyjęto założenie, że ma on wyłączną kontrolę nad dojściem.FileStream
assumes that it has exclusive control over the handle. Odczyt, zapis lub wyszukiwanie w czasie, w którym FileStream
znajduje się również dojście może spowodować uszkodzenie danych.Reading, writing, or seeking while a FileStream
is also holding a handle could result in data corruption. W celu zapewnienia bezpieczeństwa danych Wywołaj Flush przed użyciem uchwytu i unikaj wywoływania jakichkolwiek metod innych niż Close
po zakończeniu korzystania z dojścia.For data safety, call Flush before using the handle, and avoid calling any methods other than Close
after you are done using the handle.
Przestroga
Podczas kompilowania zestawu znaków przy użyciu określonego ustawienia kulturowego i pobierania tych samych znaków przy użyciu innego ustawienia kulturowego znaki mogą nie być interpretowane i mogą powodować wyjątek.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.Read
jest wartością domyślną dla tych FileStream konstruktorów bez FileShare
parametru.FileShare.Read
is the default for those FileStream constructors without a FileShare
parameter.
Aby uzyskać listę typowych operacji związanych z plikami i katalogami, zobacz typowe zadania we/wy.For a list of common file and directory operations, see Common I/O Tasks.
Zobacz też
- We/Wy plików i strumieniFile and Stream I/O
- Instrukcje: Odczytywanie tekstu z plikuHow to: Read Text from a File
- Instrukcje: Zapisywanie tekstu w plikuHow to: Write Text to a File