다음을 통해 공유


FileStream 클래스

파일에 대해 Stream을 제공하여 동기 및 비동기 읽기/쓰기 작업을 모두 지원합니다.

네임스페이스: System.IO
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public Class FileStream
    Inherits Stream
‘사용 방법
Dim instance As FileStream
[ComVisibleAttribute(true)] 
public class FileStream : Stream
[ComVisibleAttribute(true)] 
public ref class FileStream : public Stream
/** @attribute ComVisibleAttribute(true) */ 
public class FileStream extends Stream
ComVisibleAttribute(true) 
public class FileStream extends Stream

설명

파일 시스템에서 파일의 읽기, 쓰기, 열기 및 닫기를 수행하는 것뿐 아니라 파이프, 표준 입력 및 표준 출력 같은 파일 관련 운영 체제 핸들을 조작려면 FileStream 클래스를 사용하십시오. 읽기와 쓰기 작업을 동기나 비동기로 지정할 수 있습니다. FileStream은 성능 향상을 위해 입력과 출력을 버퍼링합니다.

FileStream 개체는 Seek 메서드를 사용하여 파일에 대한 임의 액세스를 지원합니다. Seek를 사용하면 읽기/쓰기 위치를 파일의 어떤 위치로도 이동할 수 있습니다. 바이트 오프셋 참조 지점 매개 변수를 사용하여 이를 수행합니다. 바이트 오프셋은 SeekOrigin 클래스의 세 가지 속성(내부 파일의 시작, 현재 위치, 또는 끝)으로 표시되는 검색 참조 지점과 관련되어 있습니다.

참고

디스크 파일은 항상 임의 액세스를 지원합니다. 해당 파일을 생성할 때 CanSeek 속성 값은 내부 파일 형식에 따라 true 또는 false로 설정됩니다. 예를 들어, winbase.h에 정의된 대로 내부 파일 형식이 FILE_TYPE_DISK이면 CanSeek 속성 값이 true이고, 그렇지 않으면 CanSeek 속성 값이 false입니다.

동기 메서드 ReadWrite와 비동기 메서드 BeginRead, BeginWrite, EndReadEndWrite는 동기 모드나 비동기 모드에서 작동할 수 있으며, 해당 모드는 이러한 메서드의 성능에 영향을 미칩니다. FileStream은 기본적으로 파일을 동기 모드에서 열지만, 비동기 모드에서도 파일을 여는 FileStream(String,FileMode,FileAccess,FileShare,Int32,Boolean) 생성자를 제공합니다.

프로세스가 파일 일부가 잠긴 상태로 종료되거나 잠금 요청이 해결되지 않은 파일을 닫으면 동작이 정의되지 않습니다.

특히 디스크 공간이 제한된 환경에서는 모든 FileStream 개체에서 Dispose 메서드를 호출해야 합니다. 사용 가능한 디스크 공간이 없고 FileStream을 종료하기 전에 Dispose 메서드를 호출하지 않은 경우 IO 작업을 수행하면 예외가 발생할 수 있습니다.

디렉터리와 다른 파일 작업에 대한 자세한 내용은 File, DirectoryPath 클래스를 참조하십시오. File 클래스는 파일 경로와 표준 입력, 표준 출력 및 표준 오류 장치를 기반으로 주로 FileStream 개체를 만들기 위한 정적 메서드가 포함된 유틸리티 클래스입니다. MemoryStream 클래스는 FileStream과 유사하게 바이트 배열과 함수로 스트림을 만듭니다.

다음 표에서는 일반적인 예 또는 관련된 I/O 작업의 예를 보여 줍니다.

수행 작업

참조 항목

텍스트 파일을 만듭니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에 씁니다.

방법: 파일에 텍스트 쓰기

텍스트 파일에서 읽습니다.

방법: 파일의 텍스트 읽기

파일에 텍스트를 추가합니다.

방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText

파일 이름을 바꾸거나 이동합니다.

File.Move

FileInfo.MoveTo

파일을 삭제합니다.

File.Delete

FileInfo.Delete

파일을 복사합니다.

File.Copy

FileInfo.CopyTo

파일 크기를 가져옵니다.

FileInfo.Length

파일 특성을 가져옵니다.

File.GetAttributes

파일의 특성을 설정합니다.

File.SetAttributes

파일이 있는지 여부를 확인합니다.

File.Exists

이진 파일에서 읽습니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

이진 파일에 씁니다.

방법: 새로 만든 데이터 파일 읽기 및 쓰기

확장명을 검색합니다.

Path.GetExtension

파일의 정규화된 경로를 검색합니다.

Path.GetFullPath

경로에서 파일 이름 및 확장명을 검색합니다.

Path.GetFileName

확장명을 변경합니다.

Path.ChangeExtension

스트림 위치 변경 감지

FileStream 개체가 해당 핸들을 단독으로 보유하고 있지 않으면 다른 스레드에서 해당 파일 핸들에 동시에 액세스하여 이 파일 핸들과 연결된 운영 체제의 파일 포인터 위치를 변경할 수 있습니다. 이 경우 FileStream 개체의 캐시된 위치와 버퍼의 캐시된 데이터가 손상될 수 있습니다. FileStream 개체는 캐시된 버퍼에 액세스하는 메서드에 대해 정기적으로 검사를 수행하여 운영 체제의 핸들 위치가 FileStream 개체에서 사용하는 캐시된 위치와 동일한지 확인합니다.

Read 메서드를 호출할 때 핸들 위치가 예기치 않게 변경되었음을 감지하면 .NET Framework에서는 해당 버퍼 내용을 삭제하고 다시 파일에서 스트림을 읽습니다. 이 경우 파일 크기와 파일 스트림의 위치에 영향을 줄 수 있는 다른 프로세스에 따라 성능에 영향을 줄 수 있습니다.

Write 메서드를 호출할 때 핸들 위치가 예기치 않게 변경되었음이 감지되면 해당 버퍼 내용이 삭제되고 IOException이 throw됩니다.

FileStream 개체는 해당 핸들을 노출하기 위해 SafeFileHandle 속성이 액세스되거나 FileStream 개체의 생성자에서 이 개체에 SafeFileHandle 속성이 지정될 경우 해당 핸들을 단독으로 보유하지 않습니다.

예제

다음 예제에서는 FileStream 생성자를 일부 보여 줍니다.

Imports System
Imports System.IO
Imports System.Text

Public Class Test

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

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

        'Create the file.
        Dim fs As FileStream = File.Create(path)

        AddText(fs, "This is some text")
        AddText(fs, "This is some more text,")
        AddText(fs, Environment.NewLine & "and this is on a new line")
        AddText(fs, Environment.NewLine & Environment.NewLine)
        AddText(fs, "The following is a subset of characters:" & Environment.NewLine)

        Dim i As Integer

        For i = 1 To 120
            AddText(fs, Convert.ToChar(i).ToString())

            'Split the output at every 10th character.
            If Math.IEEERemainder(Convert.ToDouble(i), 10) = 0 Then
                AddText(fs, Environment.NewLine)
            End If
        Next

        fs.Close()

        'Open the stream and read it back.
        fs = File.OpenRead(path)
        Dim b(1024) 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

    Private Shared Sub AddText(ByVal fs As FileStream, ByVal value As String)
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(value)
        fs.Write(info, 0, info.Length)
    End Sub
End Class
using System;
using System.IO;
using System.Text;

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

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

        //Create the file.
        using (FileStream fs = File.Create(path)) 
        {
            AddText(fs, "This is some text");
            AddText(fs, "This is some more text,");
            AddText(fs, "\r\nand this is on a new line");
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

            for (int i=1;i < 120;i++) 
            {
                AddText(fs, Convert.ToChar(i).ToString());

                //Split the output at every 10th character.
                if (Math.IEEERemainder(Convert.ToDouble(i), 10) == 0) 
                {
                    AddText(fs, "\r\n");
                }
            }
        }

        //Open the stream and read it back.
        using (FileStream fs = File.OpenRead(path)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }
        }
    }

    private static void AddText(FileStream fs, string value) 
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }
}
using namespace System;
using namespace System::IO;
using namespace System::Text;

void AddText( FileStream^ fs, String^ value )
{
   array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
   fs->Write( info, 0, info->Length );
}

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   
   // Delete the file if it exists.
   if ( File::Exists( path ) )
   {
      File::Delete( path );
   }

   //Create the file.
   {
      FileStream^ fs = File::Create( path );
      try
      {
         AddText( fs, "This is some text" );
         AddText( fs, "This is some more text," );
         AddText( fs, "\r\nand this is on a new line" );
         AddText( fs, "\r\n\r\nThe following is a subset of characters:\r\n" );
         for ( int i = 1; i < 120; i++ )
         {
            AddText( fs, Convert::ToChar( i ).ToString() );
            
            //Split the output at every 10th character.
            if ( Math::IEEERemainder( Convert::ToDouble( i ), 10 ) == 0 )
            {
               AddText( fs, "\r\n" );
            }
         }
      }
      finally
      {
         if ( fs )
            delete (IDisposable^)fs;
      }
   }
   
   //Open the stream and read it back.
   {
      FileStream^ fs = File::OpenRead( path );
      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;
      }
   }
}
import System.*;
import System.IO.*;
import System.Text.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path)) {
            File.Delete(path);
        }
        
        //Create the file.
        {
            FileStream fs = File.Create(path);
            try {
                AddText(fs, "This is some text");
                AddText(fs, "This is some more text,");
                AddText(fs, "\r\nand this is on a new line");
                AddText(fs, 
                    "\r\n\r\nThe following is a subset of characters:\r\n");
                for (int i = 1; i < 120; i++) {
                    AddText(fs, System.Convert.ToString((char)i));

                    //Split the output at every 10th character.
                    if (Math.IEEEremainder(Convert.ToDouble(i), 10) == 0) {
                        AddText(fs, "\r\n");
                    }
                }
            }
            finally {
                fs.Dispose();
            }
        }
        //Open the stream and read it back.
        {
            FileStream fs = File.OpenRead(path);
            try {
                ubyte b[] = new ubyte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);
                while (fs.Read(b, 0, b.length) > 0) {
                    Console.WriteLine(temp.GetString(b));
                }
            }
            finally {
                fs.Dispose();
            }
        }
    } //main

    private static void AddText(FileStream fs, String value)
    {
        ubyte info[] = (new UTF8Encoding(true)).GetBytes(value);
        fs.Write(info, 0, info.length);
    } //AddText
} //Test

다음 예제에서는 파일을 열거나 파일이 없으면 파일을 만든 다음 해당 파일의 끝에 정보를 추가합니다.

Imports System
Imports System.IO
Imports System.Text

Class FSOpenWrite

    Public Shared Sub Main()
        Dim fs As New FileStream("c:\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write)
        fs.Close()
        Dim sw As New StreamWriter("c:\Variables.txt", True, Encoding.ASCII)
        Dim NextLine As String = "This is the appended text."
        sw.Write(NextLine)
        sw.Close()
    End Sub 'Main
End Class 'FSOpenWrite
using System;
using System.IO;
using System.Text;

class FSOpenWrite
{
    public static void Main()
    {
        FileStream fs=new FileStream("c:\\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
        fs.Close();
        StreamWriter sw=new StreamWriter("c:\\Variables.txt", true, Encoding.ASCII);
        string NextLine="This is the appended line.";
        sw.Write(NextLine);
        sw.Close();
    }
}
using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   FileStream^ fs = gcnew FileStream( "c:\\Variables.txt",FileMode::Append,FileAccess::Write,FileShare::Write );
   fs->Close();
   StreamWriter^ sw = gcnew StreamWriter( "c:\\Variables.txt",true,Encoding::ASCII );
   String^ NextLine = "This is the appended line.";
   sw->Write( NextLine );
   sw->Close();
}

상속 계층 구조

System.Object
   System.MarshalByRefObject
     System.IO.Stream
      System.IO.FileStream
         System.IO.IsolatedStorage.IsolatedStorageFileStream

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

FileStream 멤버
System.IO 네임스페이스
File 클래스
FileAccess 열거형
FileMode 열거형
FileShare 열거형

기타 리소스

파일 및 스트림 I/O
방법: 파일의 텍스트 읽기
방법: 파일에 텍스트 쓰기
기본 파일 I/O
방법: 새로 만든 데이터 파일 읽기 및 쓰기