FileInfo.Open 메서드

정의

다양한 읽기/쓰기 및 공유 권한이 있는 파일을 엽니다.

오버로드

Name Description
Open(FileMode)

지정된 모드에서 파일을 엽니다.

Open(FileStreamOptions)

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

Open(FileMode, FileAccess)

읽기, 쓰기 또는 읽기/쓰기 권한이 있는 지정된 모드에서 파일을 엽니다.

Open(FileMode, FileAccess, FileShare)

읽기, 쓰기 또는 읽기/쓰기 액세스 권한과 지정된 공유 옵션을 사용하여 지정된 모드에서 파일을 엽니다.

Open(FileMode)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

지정된 모드에서 파일을 엽니다.

public:
 System::IO::FileStream ^ Open(System::IO::FileMode mode);
public System.IO.FileStream Open(System.IO.FileMode mode);
member this.Open : System.IO.FileMode -> System.IO.FileStream
Public Function Open (mode As FileMode) As FileStream

매개 변수

mode
FileMode

FileMode 파일을 열 모드(예: Open 또는Append)를 지정하는 상수입니다.

반품

읽기/쓰기 액세스 권한이 있고 공유되지 않은 지정된 모드에서 열린 파일입니다.

예외

파일을 찾을 수 없습니다.

파일이 읽기 전용이거나 디렉터리입니다.

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

파일이 이미 열려 있습니다.

예제

다음 예제에서는 파일을 열고 파일에 일부 정보를 추가하고 파일을 읽습니다.

using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                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 = fi.Open(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));
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim fi As FileInfo = New FileInfo(path)
        Dim fs As FileStream

        ' Delete the file if it exists.
        If fi.Exists = False Then
            'Create the file.
            fs = fi.Create()
            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)
            fs.Close()
        End If

        'Open the stream and read it back.
        fs = fi.Open(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
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is some text in the file.
'
'
'
'
'
'
'
'
'
'
'
'

추가 정보

적용 대상

Open(FileStreamOptions)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

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

public:
 System::IO::FileStream ^ Open(System::IO::FileStreamOptions ^ options);
public System.IO.FileStream Open(System.IO.FileStreamOptions options);
member this.Open : System.IO.FileStreamOptions -> System.IO.FileStream
Public Function Open (options As FileStreamOptions) As FileStream

매개 변수

options
FileStreamOptions

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

반품

열린 파일을 래핑하는 A FileStream 입니다.

설명

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

적용 대상

Open(FileMode, FileAccess)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

읽기, 쓰기 또는 읽기/쓰기 권한이 있는 지정된 모드에서 파일을 엽니다.

public:
 System::IO::FileStream ^ Open(System::IO::FileMode mode, System::IO::FileAccess access);
public System.IO.FileStream Open(System.IO.FileMode mode, System.IO.FileAccess access);
member this.Open : System.IO.FileMode * System.IO.FileAccess -> System.IO.FileStream
Public Function Open (mode As FileMode, access As FileAccess) As FileStream

매개 변수

mode
FileMode

FileMode 파일을 열 모드(예: Open 또는Append)를 지정하는 상수입니다.

access
FileAccess

FileAccess 또는 파일 액세스를 사용하여 파일을 ReadWriteReadWrite 열지 여부를 지정하는 상수입니다.

반품

FileStream 지정된 모드 및 액세스에서 열리고 공유되지 않은 개체입니다.

예외

호출자에게 필요한 권한이 없습니다.

파일을 찾을 수 없습니다.

Name 가 읽기 전용이거나 디렉터리인 경우

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

파일이 이미 열려 있습니다.

Name 가 비어 있거나 공백만 포함됩니다.

하나 이상의 인수가 null입니다.

예제

다음 예제에서는 파일을 읽기 전용으로 열고 파일에서 읽습니다.

using System;
using System.IO;
using System.Text;

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

        // Delete the file if it exists.
        if (!fi.Exists)
        {
            //Create the file.
            using (FileStream fs = fi.Create())
            {
                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 = fi.Open(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());
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
//
//
//
//
//
//
//
//
//
//
//
//
//Writing was disallowed, as expected: System.NotSupportedException: Stream does
//not support writing.
//   at System.IO.__Error.WriteNotSupported()
//   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
//   at Test.Main() in C:\Documents and Settings\My Computer\My Documents\
//Visual Studio 2005\Projects\finfo open2\finfo open2\Program.cs:line 39
imports System.IO
imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\MyTest.txt"
        Dim fi As FileInfo = new FileInfo(path)
        Dim fs As FileStream

        ' Delete the file if it exists.
        If fi.Exists = False
            'Create the file.
            fs = fi.Create()
            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)
            fs.Close()
        End If

        'Open the stream and read it back.
        fs = fi.Open(FileMode.Open, FileAccess.Read)
        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
                fs.Write(b,0,b.Length)
                Catch e As Exception
                Console.WriteLine("Writing was disallowed, as expected: {0}", e.ToString())
            End Try
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'This is some text in the file.
'
'
'
'
'
'
'
'
'
'
'
'
'Writing was disallowed, as expected: System.NotSupportedException: Stream does 
'not support writing.
'   at System.IO.__Error.WriteNotSupported()
'   at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
'   at VB_Console_Application.Test.Main() in C:\Documents and Settings\MyComputer
'\My Documents\Visual Studio 2005\Projects\finfo open2\finfo open2\Module1.vb:line 34
'

추가 정보

적용 대상

Open(FileMode, FileAccess, FileShare)

Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs
Source:
FileInfo.cs

읽기, 쓰기 또는 읽기/쓰기 액세스 권한과 지정된 공유 옵션을 사용하여 지정된 모드에서 파일을 엽니다.

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

매개 변수

mode
FileMode

FileMode 파일을 열 모드(예: Open 또는Append)를 지정하는 상수입니다.

access
FileAccess

FileAccess 또는 파일 액세스를 사용하여 파일을 ReadWriteReadWrite 열지 여부를 지정하는 상수입니다.

share
FileShare

FileShare 다른 FileStream 개체가 이 파일에 액세스하는 형식을 지정하는 상수입니다.

반품

FileStream 지정된 모드, 액세스 및 공유 옵션을 사용하여 열린 개체입니다.

예외

호출자에게 필요한 권한이 없습니다.

파일을 찾을 수 없습니다.

Name 가 읽기 전용이거나 디렉터리인 경우

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

파일이 이미 열려 있습니다.

Name 가 비어 있거나 공백만 포함됩니다.

하나 이상의 인수가 null입니다.

예제

다음 예제에서는 읽기 및 쓰기를 위해 파일을 열지만 다른 사용자 또는 프로세스에 대한 액세스를 허용하지 않는 방법을 보여 줍니다.

using System;
using System.IO;

public class OpenTest
{
    public static void Main()
    {
        // Open an existing file, or create a new one.
        FileInfo fi = new FileInfo("temp.txt");

        // Open the file just specified such that no one else can use it.
        FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );

        // Create another reference to the same file.
        FileInfo nextfi = new FileInfo("temp.txt");

        try
        {
            // Try opening the same file, which was locked by the previous process.
            nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );

            Console.WriteLine("The file was not locked, and was opened by a second process.");
        }
        catch (IOException)
        {
            Console.WriteLine("The file could not be opened because it was locked by another process.");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        // Close the file so it can be deleted.
        fs.Close();
    }
}

//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The file could not be opened because it was locked by another process.
Imports System.IO

Public Class OpenTest

    Public Shared Sub Main()
        ' Open an existing file, or create a new one.
        Dim fi As New FileInfo("temp.txt")

        ' Open the file just specified such that no one else can use it.
        Dim fs As FileStream = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)

        ' Create another reference to the same file.
        Dim nextfi As New FileInfo("temp.txt")

        Try
            ' Try opening the same file, which was locked by the previous process.
            nextfi.Open(FileMode.OpenOrCreate, FileAccess.Read)
            Console.WriteLine("The file was not locked, and was opened by a second process.")
        Catch i as IOException
            Console.WriteLine(i.ToString())
        Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try

        ' Close the file so it can be deleted.
        fs.Close()
    End Sub
End Class
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'System.IO.IOException: The process cannot access the file 
''C:\Documents and Settings\mydirectory\My Documents\Visual Studio 2005
'\Projects\fileinfoopen\fileinfoopen\obj\Release\temp.txt' 
'because it is being used by another process.
'at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
'at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, 
'Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
'options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
'at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access,
'FileShare share) at System.IO.FileInfo.Open(FileMode mode, FileAccess access)
'at VB_Console_Application.OpenTest.Main() in C:\Documents and Settings
'\mydirectory\My Documents\Visual Studio 2005\Projects\VB_Console_Application
'\VB_Console_Application\Module1.vb:line 19

추가 정보

적용 대상