FileStream 생성자

정의

FileStream 클래스의 새 인스턴스를 초기화합니다.

오버로드

FileStream(SafeFileHandle, FileAccess)

지정된 읽기/쓰기 권한을 사용하여 지정된 파일 핸들에 대한 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 경로, 생성 모드, 액세스 및 공유 권한, 버퍼 크기, 추가 파일 옵션, 액세스 제어 및 감사 보안을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 경로, 생성 모드, 액세스 및 공유 권한, 버퍼 크기 및 추가 파일 옵션을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 같은 파일에 대한 다른 FileStream의 액세스 권한, 버퍼 크기 및 추가 파일 옵션을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기를 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

지정된 읽기/쓰기 권한, FileStream 인스턴스 소유권, 버퍼 크기 및 동기/비동기 상태를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(String, FileMode, FileAccess, FileShare)

지정된 경로, 생성 모드, 읽기/쓰기 권한 및 공유 권한을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(IntPtr, FileAccess, Boolean, Int32)
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

지정된 읽기/쓰기 권한, FileStream 인스턴스 소유권 및 버퍼 크기를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기 및 동기/비동기 상태를 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(String, FileMode, FileAccess)

지정된 경로, 생성 모드 및 읽기/쓰기 권한을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(IntPtr, FileAccess, Boolean)
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

지정된 읽기/쓰기 권한 및 FileStream 인스턴스 소유권을 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(SafeFileHandle, FileAccess, Int32)

지정된 읽기/쓰기 권한 및 버퍼 크기를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

지정된 읽기/쓰기 권한, 버퍼 크기 및 동기/비동기 상태를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(String, FileStreamOptions)

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기, 추가 파일 옵션, 사전 할당 크기 및 다른 FileStreams가 동일한 파일에 대해 가질 수 있는 액세스 권한을 사용하여 클래스의 새 인스턴스 FileStream 를 초기화합니다.

FileStream(String, FileMode)

지정된 경로 및 생성 모드들 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(IntPtr, FileAccess)
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

지정된 읽기/쓰기 권한을 사용하여 지정된 파일 핸들에 대한 FileStream 클래스의 새 인스턴스를 초기화합니다.

FileStream(SafeFileHandle, FileAccess)

지정된 읽기/쓰기 권한을 사용하여 지정된 파일 핸들에 대한 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
SafeFileHandle

현재 FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

예외

accessFileAccess의 필드가 아닌 경우

호출자에게 필요한 권한이 없는 경우

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

Close 호출되면 핸들도 닫혀 파일의 핸들 수가 감소합니다.

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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

지정된 경로, 생성 모드, 액세스 및 공유 권한, 버퍼 크기, 추가 파일 옵션, 액세스 제어 및 감사 보안을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

rights
FileSystemRights

파일에 대한 액세스 및 감사 규칙을 만드는 데 사용할 액세스 권한을 결정하는 열거형 값의 비트 조합입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

options
FileOptions

추가 파일 옵션을 지정하는 열거형 값의 비트 조합입니다.

fileSecurity
FileSecurity

파일의 액세스 제어 및 감사 보안을 결정하는 개체입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

bufferSize가 음수이거나 0인 경우

또는 mode, access 또는 share에 잘못된 값이 포함된 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

또는 optionsEncrypted가 지정되었고 현재 플랫폼에서 파일 암호화가 지원되지 않는 경우

지정된 path나 파일 이름 또는 둘 모두가 시스템에 정의된 최대 길이를 초과하는 경우

현재 운영 체제가 Windows NT 이상이 아닙니다.

예제

다음 예제에서는 파일에 데이터를 쓴 다음 개체를 사용하여 FileStream 데이터를 읽습니다.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



Module FileStreamExample

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

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

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

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

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

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

            ' Close the stream.
            fWrite.Close()


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

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

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

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

            ' Close the stream.
            fRead.Close()

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

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

        Console.ReadLine()

    End Sub
End Module

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

FileStream 생성자를 사용하여 파일을 만들 때 액세스 권한을 적용합니다. 기존 파일에 대한 권한에 액세스하거나 수정하려면 해당 및 SetAccessControl 메서드를 GetAccessControl 사용하는 것이 좋습니다.

매개 fileOptions 변수는 개체를 만들 FileStream 때 활용할 수 있는 고급 작업에 대한 액세스를 제공하는 데 사용됩니다.

매개 변수는 path UNC(범용 명명 규칙) 공유의 파일을 포함하여 파일 이름이 될 수 있습니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

중요

이 생성자는 .NET Core에 없습니다. 대신 .NET Core 3.1부터 어셈블리 Create(FileInfo, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)내에서 클래스의 FileSystemAclExtensions 다음 확장 메서드를 System.Security.AccessControl 사용할 수 있습니다.

추가 정보

적용 대상

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

지정된 경로, 생성 모드, 액세스 및 공유 권한, 버퍼 크기 및 추가 파일 옵션을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

rights
FileSystemRights

파일에 대한 액세스 및 감사 규칙을 만드는 데 사용할 액세스 권한을 결정하는 열거형 값의 비트 조합입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

options
FileOptions

추가 파일 옵션을 지정하는 열거형 값의 비트 조합입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

bufferSize가 음수이거나 0인 경우

또는 mode, access 또는 share에 잘못된 값이 포함된 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

현재 운영 체제가 Windows NT 이상이 아닙니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

또는 optionsEncrypted가 지정되었고 현재 플랫폼에서 파일 암호화가 지원되지 않는 경우

지정된 path나 파일 이름 또는 둘 모두가 시스템에 정의된 최대 길이를 초과하는 경우

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

FileStream 생성자를 사용하여 파일을 만들 때 액세스 권한을 적용합니다. 기존 파일에 대한 권한에 액세스하거나 수정하려면 해당 및 SetAccessControl 메서드를 GetAccessControl 사용하는 것이 좋습니다.

매개 fileOptions 변수는 개체를 만들 FileStream 때 활용할 수 있는 고급 작업에 대한 액세스를 제공하는 데 사용됩니다.

매개 변수는 path UNC(범용 명명 규칙) 공유의 파일을 포함하여 파일 이름이 될 수 있습니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 같은 파일에 대한 다른 FileStream의 액세스 권한, 버퍼 크기 및 추가 파일 옵션을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

access
FileAccess

FileStream 개체가 파일에 액세스하는 방법을 결정하는 열거형 값의 비트 조합입니다. 또한 FileStream 개체의 CanReadCanWrite 속성에서 반환하는 값을 결정합니다. path가 디스크 파일을 지정하면 CanSeektrue입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

options
FileOptions

추가 파일 옵션을 지정하는 열거형 값의 비트 조합입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

bufferSize가 음수이거나 0인 경우

또는 mode, access 또는 share에 잘못된 값이 포함된 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

또는 optionsEncrypted가 지정되었고 현재 플랫폼에서 파일 암호화가 지원되지 않는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

예제

다음 예제에서는 파일에 데이터를 쓴 다음 개체를 사용하여 FileStream 데이터를 읽습니다.

#using <System.dll>

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



Module FileStreamExample

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

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

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

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

            ' Close the stream.
            fWrite.Close()


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

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

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

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

            ' Close the stream.
            fRead.Close()

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

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

        Console.ReadLine()

    End Sub
End Module

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 fileOptions 변수는 개체를 만들 FileStream 때 활용할 수 있는 고급 작업에 대한 액세스를 제공하는 데 사용됩니다.

매개 변수는 path UNC(범용 명명 규칙) 공유의 파일을 포함하여 파일 이름이 될 수 있습니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기를 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

access
FileAccess

FileStream 개체가 파일에 액세스하는 방법을 결정하는 열거형 값의 비트 조합입니다. 또한 FileStream 개체의 CanReadCanWrite 속성에서 반환하는 값을 결정합니다. path가 디스크 파일을 지정하면 CanSeektrue입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

bufferSize가 음수이거나 0인 경우

또는 mode, access 또는 share에 잘못된 값이 포함된 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 변수는 path UNC(범용 명명 규칙) 공유의 파일을 포함하여 파일 이름이 될 수 있습니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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

주의

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

주의

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

주의

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

주의

Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead

지정된 읽기/쓰기 권한, FileStream 인스턴스 소유권, 버퍼 크기 및 동기/비동기 상태를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
IntPtr

nativeint

FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

ownsHandle
Boolean

FileStream인스턴스가 파일 핸들을 소유하면 true이고, 그렇지 않으면 false입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

isAsync
Boolean

겹쳐진 I/O 모드에서 핸들이 비동기적으로 열렸으면 true이고, 그렇지 않으면 false입니다.

특성

예외

accessFileAccess.Read보다 작거나 FileAccess.ReadWrite보다 큰 경우. 또는 bufferSize가 0보다 작거나 같은 경우

핸들이 잘못되었습니다.

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

개체에 FileStream 지정된 파일에 대한 액세스 권한이 부여됩니다. 핸들의 소유권은 지정된 대로 지정됩니다. 핸들 FileStream 을 소유하는 경우 메서드에 대한 Close 호출도 핸들을 닫습니다. 특히 파일의 핸들 수는 감소합니다. 개체에 FileStream 지정된 버퍼 크기가 지정됩니다.

FileStream 는 핸들을 단독으로 제어할 수 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다. 또는 이 FileStream 생성자를 호출하기 전에 핸들을 읽고 씁니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(String, FileMode, FileAccess, FileShare)

지정된 경로, 생성 모드, 읽기/쓰기 권한 및 공유 권한을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

access
FileAccess

FileStream 개체가 파일에 액세스하는 방법을 결정하는 열거형 값의 비트 조합입니다. 또한 FileStream 개체의 CanReadCanWrite 속성에서 반환하는 값을 결정합니다. path가 디스크 파일을 지정하면 CanSeektrue입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

mode에 잘못된 값이 포함된 경우

예제

이 코드 예제는에 대해 제공 된 큰 예제의 일부는 Lock 메서드.

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

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 변수는 path UNC(유니버설 명명 규칙) 공유의 파일을 포함하여 파일 이름일 수 있습니다.

생성자에는 파일에 대한 읽기/쓰기 액세스 권한이 부여되고 읽기 액세스 공유가 열립니다(즉, 개체가 닫혀 있지만 읽기 시도가 성공할 때까지 FileStream 이 프로세스 또는 다른 프로세스에서 쓰기 위해 파일을 여는 요청이 실패함). 버퍼 크기는 기본 크기 4096바이트(4KB)로 설정됩니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(IntPtr, FileAccess, Boolean, Int32)

주의

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

주의

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

주의

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

주의

Use FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead

지정된 읽기/쓰기 권한, FileStream 인스턴스 소유권 및 버퍼 크기를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
IntPtr

nativeint

FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

ownsHandle
Boolean

FileStream인스턴스가 파일 핸들을 소유하면 true이고, 그렇지 않으면 false입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

특성

예외

bufferSize가 음수입니다.

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

개체에 FileStream 지정된 파일에 대한 액세스 권한이 부여됩니다. 핸들의 소유권은 지정된 대로 지정됩니다. 핸들 FileStream 을 소유하는 경우 메서드에 대한 Close 호출도 핸들을 닫습니다. 특히 파일의 핸들 수는 감소합니다. 개체에 FileStream 지정된 버퍼 크기가 지정됩니다.

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다. 또는 이 FileStream 생성자를 호출하기 전에 핸들을 읽고 씁니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

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

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기 및 동기/비동기 상태를 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

access
FileAccess

FileStream 개체가 파일에 액세스하는 방법을 결정하는 열거형 값의 비트 조합입니다. 또한 FileStream 개체의 CanReadCanWrite 속성에서 반환하는 값을 결정합니다. path가 디스크 파일을 지정하면 CanSeektrue입니다.

share
FileShare

프로세스에서 파일을 공유하는 방법을 결정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

useAsync
Boolean

비동기 I/O 또는 동기 I/O를 사용할지를 지정합니다. 그러나 내부 운영 체제에서 비동기 I/O가 지원되지 않을 수도 있으므로 true를 지정해도 플랫폼에 따라 핸들이 동기적으로 열릴 수 있습니다. 비동기적으로 열린 경우 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 메서드는 대량의 데이터를 읽거나 쓸 때는 보다 효과적이지만 소량의 데이터를 읽거나 쓸 경우 작업 속도가 훨씬 느려질 수 있습니다. 애플리케이션이 비동기 I/O를 사용하도록 디자인된 경우 useAsync 매개 변수를 true로 설정합니다. 비동기 I/O를 올바르게 사용하면 애플리케이션의 속도가 10배 정도 향상될 수 있지만 애플리케이션을 비동기 I/O에 맞도록 다시 디자인하지 않고 사용하면 성능이 10배 정도 감소될 수도 있습니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

bufferSize가 음수이거나 0인 경우

또는 mode, access 또는 share에 잘못된 값이 포함된 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

예제

다음 코드 예제에서는 파일에 데이터를 비동기적으로 쓴 다음 데이터가 올바르게 작성되었는지 확인하는 방법을 보여 있습니다. State 주 스레드에서 메서드 EndWriteCallback 로 정보를 전달하기 위해 개체가 EndReadCallback 만들어집니다.

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

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 변수는 path UNC(범용 명명 규칙) 공유의 파일을 포함하여 파일 이름이 될 수 있습니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(String, FileMode, FileAccess)

지정된 경로, 생성 모드 및 읽기/쓰기 권한을 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

access
FileAccess

FileStream 개체가 파일에 액세스하는 방법을 결정하는 열거형 값의 비트 조합입니다. 또한 FileStream 개체의 CanReadCanWrite 속성에서 반환하는 값을 결정합니다. path가 디스크 파일을 지정하면 CanSeektrue입니다.

예외

path이(가) null인 경우

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

accessWrite 또는 ReadWrite이고 파일 또는 디렉터리가 읽기 전용 액세스로 설정된 경우처럼, 지정된 path에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

mode에 잘못된 값이 포함된 경우

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 변수는 path UNC(유니버설 명명 규칙) 공유의 파일을 포함하여 파일 이름일 수 있습니다.

생성자에는 파일에 대한 읽기/쓰기 액세스 권한이 부여되고 읽기 액세스 공유가 열립니다(즉, 개체가 닫혀 있지만 읽기 시도가 성공할 때까지 FileStream 이 프로세스 또는 다른 프로세스에서 쓰기 위해 파일을 여는 요청이 실패함). 버퍼 크기는 기본 크기 4096바이트(4KB)로 설정됩니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(IntPtr, FileAccess, Boolean)

주의

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

주의

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

주의

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

주의

Use FileStream(SafeFileHandle handle, FileAccess access) instead

지정된 읽기/쓰기 권한 및 FileStream 인스턴스 소유권을 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
IntPtr

nativeint

현재 FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

ownsHandle
Boolean

FileStream인스턴스가 파일 핸들을 소유하면 true이고, 그렇지 않으면 false입니다.

특성

예외

accessFileAccess의 필드가 아닌 경우

호출자에게 필요한 권한이 없는 경우

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

개체에 FileStream 지정된 파일에 대한 액세스 권한이 부여됩니다. 핸들의 소유권은 지정된 대로 지정됩니다. 이 프로세스가 핸들을 소유하는 경우 메서드 호출 Close 도 핸들을 닫고 파일의 핸들 수가 감소합니다. 개체에는 FileStream 4096바이트의 기본 버퍼 크기가 지정됩니다.

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(SafeFileHandle, FileAccess, Int32)

지정된 읽기/쓰기 권한 및 버퍼 크기를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
SafeFileHandle

현재 FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 FileAccess 상수입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

예외

handle 매개 변수가 잘못된 핸들인 경우

또는 handle 매개 변수가 동기식 핸들인데 비동기식으로 사용된 경우

bufferSize 매개 변수가 음수인 경우

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다. 또는 이 FileStream 생성자를 호출하기 전에 핸들을 읽고 씁니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

지정된 읽기/쓰기 권한, 버퍼 크기 및 동기/비동기 상태를 사용하여 지정된 파일 핸들에 대해 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
SafeFileHandle

FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

bufferSize
Int32

버퍼 크기를 나타내는 0보다 큰 양의 Int32 값입니다. 기본 버퍼 크기는 4,096입니다.

isAsync
Boolean

겹쳐진 I/O 모드에서 핸들이 비동기적으로 열렸으면 true이고, 그렇지 않으면 false입니다.

예외

handle 매개 변수가 잘못된 핸들인 경우

또는 handle 매개 변수가 동기식 핸들인데 비동기식으로 사용된 경우

bufferSize 매개 변수가 음수인 경우

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

호출자에게 필요한 권한이 없는 경우

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

파일 핸들을 isAsync 비동기적으로 열도록 true 매개 변수를 설정합니다. 매개 변수가 있으면 스트림은 true겹치는 I/O를 사용하여 파일 작업을 비동기적으로 수행합니다. 그러나 매개 변수는 , WriteAsync또는 CopyToAsync 메서드를 호출ReadAsynctrue 필요가 없습니다. isAsync 매개 변수가 false 있고 비동기 읽기 및 쓰기 작업을 호출하는 경우 UI 스레드는 여전히 차단되지 않지만 실제 I/O 작업은 동기적으로 수행됩니다.

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다. 또는 이 FileStream 생성자를 호출하기 전에 핸들을 읽고 씁니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(String, FileStreamOptions)

지정된 경로, 생성 모드, 읽기/쓰기 및 공유 권한, 버퍼 크기, 추가 파일 옵션, 사전 할당 크기 및 다른 FileStreams가 동일한 파일에 대해 가질 수 있는 액세스 권한을 사용하여 클래스의 새 인스턴스 FileStream 를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 인스턴스가 캡슐화할 파일에 대한 상대 또는 절대 경로입니다.

options
FileStreamOptions

사용할 선택적 FileStream 매개 변수를 설명하는 개체입니다.

예외

path 또는 optionsnull인 경우

path 은 빈 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는

path 는 NTFS 환경에서 CON:, COM1:또는 LPT1:과 같은 비 파일 디바이스를 나타냅니다.

path 는 비 NTFS 환경에서 CON:, COM1:, LPT1:등과 같은 비 파일 디바이스를 나타냅니다.

예를 들어, ModeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는

스트림이 닫혔습니다.

또는

디스크가 가득 찼습니다(제공되고 path 일반 파일을 가리키는 경우PreallocationSize).

또는

파일이 너무 큽니다(제공되고 path 일반 파일을 가리키는 경우PreallocationSize).

호출자에게 필요한 권한이 없는 경우

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

요청은 Access 운영 체제에서 지정된 path경우 또는 파일 또는 ReadWrite 디렉터리가 읽기 전용 액세스로 설정된 경우 Access Write 와 같이 허용되지 않습니다.

또는

Encrypted 에 대해 Options 지정되었지만 파일 암호화는 현재 플랫폼에서 지원되지 않습니다.

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

설명

값을 지정하면 사전 할당 크기에 대한 PreallocationSize 힌트를 제공하지만 강력한 보장은 제공하지 않습니다. 전체 사용량에 대한 자세한 내용은 설명서를 PreallocationSize참조하세요.

적용 대상

FileStream(String, FileMode)

지정된 경로 및 생성 모드들 사용하여 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

path
String

현재 FileStream 개체가 캡슐화할 파일의 상대 또는 절대 경로입니다.

mode
FileMode

파일을 열거나 만드는 방법을 결정하는 열거형 값 중 하나입니다.

예외

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 빈 문자열("")이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다.

또는 path가 NTFS 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path가 NTFS 이외의 환경에서 파일이 아닌 디바이스(예: "con:", "com1:", "lpt1:" 등)를 참조하는 경우

path이(가) null인 경우

호출자에게 필요한 권한이 없는 경우

예를 들어, modeFileMode.Truncate 또는 FileMode.Open인 경우 파일을 찾을 수 없으며 path로 지정된 파일이 없는 경우. 이러한 모드에는 이 파일이 이미 있어야 합니다.

path가 읽기 전용 파일을 지정합니다.

path로 지정한 파일이 이미 있는 경우에 FileMode.CreateNew를 지정하는 등의 I/O 오류가 발생한 경우

또는 스트림이 닫혔습니다.

지정된 경로가 잘못되었습니다(예: 매핑되지 않은 드라이브에 있음).

지정된 경로, 파일 이름 또는 둘 다가 시스템에서 정의한 최대 길이를 초과합니다.

mode에 잘못된 값이 포함된 경우

예제

다음 코드 예제에서는 파일에 데이터를 쓰고 바이트 바이트를 기록한 다음 데이터가 올바르게 작성되었는지 확인하는 방법을 보여줍니다.

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

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

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

}
using System;
using System.IO;

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

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

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

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

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

Class FStream

    Shared Sub Main()

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

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

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

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

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

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

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

설명

.NET Framework와 같은 디바이스 이름에는 경로 통해 실제 디스크에 직접 액세스를 지원 하지 않습니다 "\\. \PHYSICALDRIVE0"입니다.

매개 변수는 path UNC(유니버설 명명 규칙) 공유의 파일을 포함하여 파일 이름일 수 있습니다.

생성자에는 파일에 대한 읽기/쓰기 액세스 권한이 부여되고 읽기 액세스 공유가 열립니다(즉, 개체가 닫혀 있지만 읽기 시도가 성공할 때까지 FileStream 이 프로세스 또는 다른 프로세스에서 쓰기 위해 파일을 여는 요청이 실패함).

이 생성자를 사용하여 읽기 전용 파일을 열 수 없습니다. 대신 값이 .로 설정된 FileAccess.Read매개 변수를 FileAccess 허용하는 생성자를 사용해야 합니다.

버퍼 크기는 기본 크기 4096바이트(4KB)로 설정됩니다.

참고

path 는 디스크에 저장된 파일일 필요가 없습니다. 스트림을 통한 액세스를 지원하는 시스템의 일부일 수 있습니다. 예를 들어 시스템에 따라이 클래스는 물리적 디바이스를 액세스할 수 있습니다.

CanSeektrue 파일을 캡슐화하는 모든 FileStream 개체에 대한 것입니다. 경우 path 검색을 지원 하지 않는 디바이스를 나타냄 합니다 CanSeek 결과 속성 FileStreamfalse합니다. 자세한 내용은 CanSeek을 참조하십시오.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

매개 변수가 FileAccess 없는 생성자의 경우 매개 변수가 mode 설정된 AppendWrite 경우 기본 액세스 권한입니다. 그렇지 않으면 액세스가 .로 설정됩니다 ReadWrite.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

FileStream(IntPtr, FileAccess)

주의

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

주의

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

주의

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

주의

Use FileStream(SafeFileHandle handle, FileAccess access) instead

지정된 읽기/쓰기 권한을 사용하여 지정된 파일 핸들에 대한 FileStream 클래스의 새 인스턴스를 초기화합니다.

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

매개 변수

handle
IntPtr

nativeint

현재 FileStream 개체가 캡슐화할 파일에 대한 파일 핸들입니다.

access
FileAccess

FileStream 개체의 CanReadCanWrite 속성을 설정하는 열거형 값의 비트 조합입니다.

특성

예외

accessFileAccess의 필드가 아닌 경우

호출자에게 필요한 권한이 없는 경우

I/O 오류(예: 디스크 오류)가 발생했습니다.

또는

스트림이 닫혔습니다.

accessWrite 또는 ReadWrite이고 파일 핸들이 읽기 전용 액세스로 설정된 경우처럼, 지정된 파일 핸들에 대해 운영 체제에서 access 요청을 허용하지 않는 경우

설명

Close 호출되면 핸들도 닫혀 파일의 핸들 수가 감소합니다.

FileStream 는 핸들에 대한 배타적 제어를 가지고 있다고 가정합니다. 핸들을 들고 있는 FileStream 동안 읽기, 쓰기 또는 검색하면 데이터가 손상될 수 있습니다. 데이터 보안을 위해 핸들을 사용하기 전에 호출 Flush 하고 핸들 사용을 완료한 후 이외의 Close 메서드를 호출하지 않습니다.

주의

특정 문화권 설정을 사용하여 문자 집합을 컴파일하고 다른 문화권 설정으로 동일한 문자를 검색하는 경우 문자를 해석할 수 없으며 예외가 throw될 수 있습니다.

FileShare.Read 는 매개 변수가 없는 생성 FileStream 자의 기본값입니다 FileShare .

일반적인 파일 및 디렉터리 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상