File.Open 메서드

정의

지정된 경로에서 FileStream을 엽니다.

오버로드

Open(String, FileMode, FileAccess, FileShare)

읽기, 쓰기 또는 읽기/쓰기 권한과 지정된 공유 옵션을 사용하여 지정된 경로에서 지정된 모드를 갖는 FileStream을 엽니다.

Open(String, FileMode)

지정된 경로에서 FileStream을 공유하지 않고 읽기/쓰기 액세스로 엽니다.

Open(String, FileStreamOptions)

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

Open(String, FileMode, FileAccess)

지정된 경로에서 FileStream을 공유하지 않고 지정된 모드와 액세스로 엽니다.

Open(String, FileMode, FileAccess, FileShare)

Source:
File.cs
Source:
File.cs
Source:
File.cs

읽기, 쓰기 또는 읽기/쓰기 권한과 지정된 공유 옵션을 사용하여 지정된 경로에서 지정된 모드를 갖는 FileStream을 엽니다.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access, System::IO::FileShare share);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);
static member Open : string * System.IO.FileMode * System.IO.FileAccess * System.IO.FileShare -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode, access As FileAccess, share As FileShare) As FileStream

매개 변수

path
String

열 파일입니다.

mode
FileMode

파일이 없는 경우 파일을 만들 것인지를 지정하고, 기존 파일 내용을 유지할 것인지 덮어쓸 것인지를 결정하는 FileMode 값입니다.

access
FileAccess

파일에 수행할 수 있는 작업을 지정하는 FileAccess 값입니다.

share
FileShare

다른 스레드가 파일에 대해 가지는 액세스 형식을 지정하는 FileShare 값입니다.

반환

읽기, 쓰기 또는 읽기/쓰기 권한과 지정된 공유 옵션을 사용하여 지정된 경로에서 지정된 모드를 갖는 FileStream을 엽니다.

예외

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

accessRead를 지정하고, modeCreate, CreateNew, Truncate 또는 Append를 지정했습니다.

path이(가) null인 경우

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

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

파일을 여는 동안 I/O 오류가 발생했습니다.

path가 읽기 전용인 파일을 지정하고 accessRead가 아닙니다.

또는

path에 디렉터리가 지정되었습니다.

또는

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

또는

modeCreate이고 지정된 파일이 숨겨진 파일입니다.

mode, access 또는 share이(가) 잘못된 값을 지정했습니다.

path에 지정된 파일을 찾을 수 없습니다.

path의 형식이 잘못되었습니다.

예제

다음 예제에서는 읽기 전용 액세스 권한이 있고 파일 공유가 허용되지 않는 파일을 엽니다.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Create the file if it does not exist.
   if (  !File::Exists( path ) )
   {
      // Create the file.
      FileStream^ fs = File::Create( path );
      try
      {
         array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
         
         // Add some information to the file.
         fs->Write( info, 0, info->Length );
      }
      finally
      {
         if ( fs )
                  delete (IDisposable^)fs;
      }
   }
   
   // Open the stream and read it back.
   FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Read, FileShare::None );
   try
   {
      array<Byte>^b = gcnew array<Byte>(1024);
      UTF8Encoding^ temp = gcnew UTF8Encoding( true );
      while ( fs->Read( b, 0, b->Length ) > 0 )
      {
         Console::WriteLine( temp->GetString( b ) );
      }
      try
      {
         // Try to get another handle to the same file.
         FileStream^ fs2 = File::Open( path, FileMode::Open );
         try
         {
            // Do some task here.
         }
         finally
         {
            if ( fs2 )
                        delete (IDisposable^)fs2;
         }
      }
      catch ( Exception^ e ) 
      {
         Console::Write( "Opening the file twice is disallowed." );
         Console::WriteLine( ", as expected: {0}", e );
      }
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Create the file if it does not exist.
        if (!File.Exists(path))
        {
            // Create the file.
            using (FileStream fs = File.Create(path))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");

                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        // Open the stream and read it back.
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }

            try
            {
                // Try to get another handle to the same file.
                using (FileStream fs2 = File.Open(path, FileMode.Open))
                {
                    // Do some task here.
                }
            }
            catch (Exception e)
            {
                Console.Write("Opening the file twice is disallowed.");
                Console.WriteLine(", as expected: {0}", e.ToString());
            }
        }
    }
}
open System.IO
open System.Text

let path = @"c:\temp\MyTest.txt"

// Create the file if it does not exist.
if File.Exists path |> not then
    // Create the file.
    use fs = File.Create path

    let info =
        UTF8Encoding(true)
            .GetBytes "This is some text in the file."

    // Add some information to the file.
    fs.Write(info, 0, info.Length)

// Open the stream and read it back.
do
    use fs =
        File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)

    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true

    while fs.Read(b, 0, b.Length) > 0 do
        printfn $"{temp.GetString b}"

    try
        // Try to get another handle to the same file.
        use fs2 = File.Open(path, FileMode.Open)
        // Do some task here.
        ()
    with
    | e -> printf "Opening the file twice is disallowed, as expected: {e}"
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    Dim path As String = "c:\temp\MyTest.txt"

    ' Create the file if it does not exist. 
    If Not File.Exists(path) Then
      ' Create the file.
      Using fs As FileStream = File.Create(path)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")

        ' Add some information to the file.
        fs.Write(info, 0, info.Length)
      End Using
    End If

    ' Open the stream and read it back.
    Using fs As FileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop

      Try
        ' Try to get another handle to the same file. 
        Using fs2 As FileStream = File.Open(path, FileMode.Open)
          ' Do some task here.
        End Using
      Catch e As Exception
        Console.Write("Opening the file twice is disallowed.")
        Console.WriteLine(", as expected: {0}", e.ToString())
      End Try

    End Using

  End Sub
End Class

설명

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Open(String, FileMode)

Source:
File.cs
Source:
File.cs
Source:
File.cs

지정된 경로에서 FileStream을 공유하지 않고 읽기/쓰기 액세스로 엽니다.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode);
static member Open : string * System.IO.FileMode -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode) As FileStream

매개 변수

path
String

열 파일입니다.

mode
FileMode

파일이 없는 경우 파일을 만들 것인지를 지정하고, 기존 파일 내용을 유지할 것인지 덮어쓸 것인지를 결정하는 FileMode 값입니다.

반환

읽기/쓰기 액세스 및 공유하지 않는 상태로 지정된 모드와 경로에서 열린 FileStream입니다.

예외

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

path이(가) null인 경우

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

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

파일을 여는 동안 I/O 오류가 발생했습니다.

path에 읽기 전용인 파일이 지정되었습니다.

또는

현재 플랫폼이 해당 작업을 지원하지 않는 경우

또는

path에 디렉터리가 지정되었습니다.

또는

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

또는

modeCreate이고 지정된 파일이 숨겨진 파일입니다.

mode가 잘못된 값을 지정했습니다.

path에 지정된 파일을 찾을 수 없습니다.

path의 형식이 잘못되었습니다.

예제

다음 코드 예제에서는 임시 파일을 만들고 일부 텍스트를 씁니다. 그런 다음, T:System.IO.FileMode.Open을 사용하여 파일을 엽니다. 즉, 파일이 아직 없으면 만들어지지 않습니다.

using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
   // Create a temporary file, and put some data into it.
   String^ path = Path::GetTempFileName();
   FileStream^ fs = File::Open( path, FileMode::Open, FileAccess::Write, FileShare::None );
   try
   {
      array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
      
      // Add some information to the file.
      fs->Write( info, 0, info->Length );
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }

   // Open the stream and read it back.
   fs = File::Open( path, FileMode::Open );
   try
   {
      array<Byte>^b = gcnew array<Byte>(1024);
      UTF8Encoding^ temp = gcnew UTF8Encoding( true );
      while ( fs->Read( b, 0, b->Length ) > 0 )
      {
         Console::WriteLine( temp->GetString( b ) );
      }
   }
   finally
   {
      if ( fs )
            delete (IDisposable^)fs;
   }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        // Create a temporary file, and put some data into it.
        string path = Path.GetTempFileName();
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (FileStream fs = File.Open(path, FileMode.Open))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }
}
open System.IO
open System.Text

// Create a temporary file, and put some data into it.
let path = Path.GetTempFileName()

do
    use fs =
        File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)

    let info =
        UTF8Encoding(true)
            .GetBytes "This is some text in the file."
    // Add some information to the file.
    fs.Write(info, 0, info.Length)

// Open the stream and read it back.
do
    use fs = File.Open(path, FileMode.Open)
    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true

    while fs.Read(b, 0, b.Length) > 0 do
        printfn $"{temp.GetString b}"
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
  
    ' Create a temporary file, and put some data into it. 
    Dim path1 As String = Path.GetTempFileName()
    Using fs As FileStream = File.Open(path1, FileMode.Open, FileAccess.Write, FileShare.None)
      Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
      ' Add some information to the file.
      fs.Write(info, 0, info.Length)
    End Using

    ' Open the stream and read it back. 
    Using fs As FileStream = File.Open(path1, FileMode.Open)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)
      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop
    End Using

  End Sub
End Class

설명

매개 변수는 path 상대 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Open(String, FileStreamOptions)

Source:
File.cs
Source:
File.cs
Source:
File.cs

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

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileStreamOptions ^ options);
public static System.IO.FileStream Open (string path, System.IO.FileStreamOptions options);
static member Open : string * System.IO.FileStreamOptions -> System.IO.FileStream
Public Shared Function Open (path As String, options As FileStreamOptions) As FileStream

매개 변수

path
String

열 파일의 경로입니다.

options
FileStreamOptions

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

반환

FileStream 열린 파일을 래핑하는 instance.

설명

FileStream(String, FileStreamOptions) 예외에 대한 정보입니다.

적용 대상

Open(String, FileMode, FileAccess)

Source:
File.cs
Source:
File.cs
Source:
File.cs

지정된 경로에서 FileStream을 공유하지 않고 지정된 모드와 액세스로 엽니다.

public:
 static System::IO::FileStream ^ Open(System::String ^ path, System::IO::FileMode mode, System::IO::FileAccess access);
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access);
static member Open : string * System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Shared Function Open (path As String, mode As FileMode, access As FileAccess) As FileStream

매개 변수

path
String

열 파일입니다.

mode
FileMode

파일이 없는 경우 파일을 만들 것인지를 지정하고, 기존 파일 내용을 유지할 것인지 덮어쓸 것인지를 결정하는 FileMode 값입니다.

access
FileAccess

파일에 수행할 수 있는 작업을 지정하는 FileAccess 값입니다.

반환

지정된 모드와 액세스 권한으로 지정된 파일에 대한 액세스를 제공하는 공유되지 않는 FileStream입니다.

예외

2.1보다 오래된 .NET Framework 및 .NET Core 버전: path 길이가 0인 문자열이거나, 공백만 포함하거나, 하나 이상의 잘못된 문자를 포함합니다. GetInvalidPathChars() 메서드를 사용하여 잘못된 문자를 쿼리할 수 있습니다.

또는

accessRead를 지정하고, modeCreate, CreateNew, Truncate 또는 Append를 지정했습니다.

path이(가) null인 경우

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

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

파일을 여는 동안 I/O 오류가 발생했습니다.

path가 읽기 전용인 파일을 지정하고 accessRead가 아닙니다.

또는

path에 디렉터리가 지정되었습니다.

또는

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

또는

modeCreate이고 지정된 파일이 숨겨진 파일입니다.

mode 또는 access가 잘못된 값을 지정합니다.

path에 지정된 파일을 찾을 수 없습니다.

path의 형식이 잘못되었습니다.

예제

다음 예제에서는 읽기 전용 액세스 권한이 있는 파일을 엽니다.


using namespace System;
using namespace System::IO;
using namespace System::Text;

int main()
{
    // This sample assumes that you have a folder named "c:\temp" on your computer.
    String^ filePath = "c:\\temp\\MyTest.txt";
    // Delete the file if it exists.
    if (File::Exists( filePath ))
    {
        File::Delete( filePath );
    }
    // Create the file.
    FileStream^ fs = File::Create( filePath );
    try
    {
        array<Byte>^ info = ( gcnew UTF8Encoding( true ))->GetBytes( "This is some text in the file." );
        
        // Add some information to the file.
        fs->Write( info, 0, info->Length );
    }
    finally
    {
        if ( fs )
            delete (IDisposable^)fs;
    }

    // Open the stream and read it back.
    fs = File::Open( filePath, FileMode::Open, FileAccess::Read );
    try
    {
        array<Byte>^ b = gcnew array<Byte>(1024);
        UTF8Encoding^ temp = gcnew UTF8Encoding( true );
        while ( fs->Read( b, 0, b->Length ) > 0 )
        {
            Console::WriteLine( temp->GetString( b ) );
        }
        try
        {
            // Try to write to the file.
            fs->Write( b, 0, b->Length );
        }
        catch ( Exception^ e ) 
        {
            Console::WriteLine( "Writing was disallowed, as expected: {0}", e->ToString() );
        }
    }
    finally
    {
        if ( fs )
            delete (IDisposable^)fs;
    }
}
using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        // This sample assumes that you have a folder named "c:\temp" on your computer.
        string filePath = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }

        // Create the file.
        using (FileStream fs = File.Create(filePath))
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0)
            {
                Console.WriteLine(temp.GetString(b));
            }

            try
            {
                // Try to write to the file.
                fs.Write(b,0,b.Length);
            }
            catch (Exception e)
            {
                Console.WriteLine("Writing was disallowed, as expected: {0}", e.ToString());
            }
        }
    }
}
open System.IO
open System.Text

// This sample assumes that you have a folder named "c:\temp" on your computer.
let filePath = @"c:\temp\MyTest.txt"

// Delete the file if it exists.
if File.Exists filePath then
    File.Delete filePath

// Create the file.
do
    use fs = File.Create filePath

    let info =
        UTF8Encoding(true)
            .GetBytes "This is some text in the file."
    // Add some information to the file.
    fs.Write(info, 0, info.Length)

// Open the stream and read it back.
do
    use fs =
        File.Open(filePath, FileMode.Open, FileAccess.Read)

    let b = Array.zeroCreate 1024
    let temp = UTF8Encoding true

    while fs.Read(b, 0, b.Length) > 0 do
        printfn $"{temp.GetString b}"

    try
        // Try to write to the file.
        fs.Write(b, 0, b.Length)
    with
    | e -> printfn $"Writing was disallowed, as expected: {e}"
Imports System.IO
Imports System.Text

Public Class Test
  Public Shared Sub Main()
    ' This sample assumes that you have a folder named "c:\temp" on your computer. 
    Dim filePath As String = "c:\temp\MyTest.txt"

    ' Delete the file if it exists. 
    If File.Exists(filePath) Then
      File.Delete(filePath)
    End If

    ' Create the file.
    Using fs As FileStream = File.Create(filePath)
      Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")

      ' Add some information to the file.
      fs.Write(info, 0, info.Length)
    End Using

    ' Open the stream and read it back.
    Using fs As FileStream = File.Open(filePath, FileMode.Open, FileAccess.Read)
      Dim b(1023) As Byte
      Dim temp As UTF8Encoding = New UTF8Encoding(True)

      ' Display the information on the console. 
      Do While fs.Read(b, 0, b.Length) > 0
        Console.WriteLine(temp.GetString(b))
      Loop

      Try
        ' Try to write to the file
        fs.Write(b, 0, b.Length)
      Catch e As Exception
        Console.WriteLine("Writing was disallowed, as expected: " & e.ToString())
      End Try

    End Using

  End Sub
End Class

설명

path 매개 변수는 상대 경로 또는 절대 경로 정보를 지정할 수 있습니다. 상대 경로 정보는 현재 작업 디렉터리를 기준으로 해석됩니다. 현재 작업 디렉터리를 가져오려면 를 참조하세요 GetCurrentDirectory.

추가 정보

적용 대상