푸터 콘텐츠로 바로가기
.NET 도움말

FileStream C# (개발자를 위한 작동 방식)

이 문서는 C#의 FileStream 클래스에 초점을 맞추며, 파일에서 읽기 및 쓰기 작업을 수행하는 데 어떻게 도움이 되는지 설명합니다. 실용적인 예제를 탐구하고, FileStream이 기본적으로 어떻게 작동하는지 이해하며, 파일 데이터를 효율적으로 관리하는 방법을 배웁니다. 이 가이드는 C#에서 파일 처리에 익숙하지 않은 사람들을 대상으로 하므로, C#의 파일 작업에 대한 자세한 지침과 IronPDF 라이브러리 소개를 제공하면서도 쉬운 언어를 사용합니다.

FileStream이란 무엇입니까?

C#의 FileStream 클래스는 바이트를 사용하여 파일을 처리하는 방법을 제공합니다. 파일의 읽기 및 쓰기 작업과 함께 작동하며 파일 내용을 직접 상호작용할 수 있습니다. 이는 특히 바이트 배열을 조작할 때 입/출력 작업을 위해 파일을 처리할 때 특히 유용합니다.

FileStream 사용 사례

FileStream은 다음에 이상적입니다:

  • 파일에서 바이너리 데이터를 직접 읽거나 쓰기.
  • 대형 파일을 효율적으로 처리.
  • 비동기 파일 작업 수행.
  • 메모리를 효율적으로 사용하여 시스템 리소스 관리.

기본 예제

다음은 파일을 열고 데이터를 기록한 후 FileStream을 사용하여 읽는 간단한 예제입니다:

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = "example.txt";

        // Creating a FileStream object to handle the file. The file handle is acquired here.
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");
            // Write data to file
            fileStream.Write(data, 0, data.Length);
        }

        // Read from the file
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            string text = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(text);
        }
    }
}
using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path = "example.txt";

        // Creating a FileStream object to handle the file. The file handle is acquired here.
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!");
            // Write data to file
            fileStream.Write(data, 0, data.Length);
        }

        // Read from the file
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            string text = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(text);
        }
    }
}
Imports System
Imports System.IO

Public Class Example
	Public Shared Sub Main()
		Dim path As String = "example.txt"

		' Creating a FileStream object to handle the file. The file handle is acquired here.
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes("Hello, FileStream!")
			' Write data to file
			fileStream.Write(data, 0, data.Length)
		End Using

		' Read from the file
		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
			Dim text As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(text)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

이 예제는 파일 읽기 및 쓰기 작업을 처리하기 위해 FileStream 개체를 생성하는 방법을 보여줍니다. FileStream 클래스는 바이트를 직접 읽고 쓰기 때문에 대형 파일이나 바이너리 데이터를 처리하기에 적합합니다. 우리는 Encoding 를 사용하여 텍스트와 바이트 간에 변환했습니다.

FileStream을 사용하여 데이터 쓰기

파일에 데이터를 쓰려면 Write 메소드를 사용합니다. 여기서는 그것이 어떻게 작동하는지를 자세히 설명하는 예제를 보여줍니다:

using System;
using System.IO;

public class FileWriteExample
{
    public static void Main()
    {
        string path = "output.txt";

        // Creating a FileStream object to write data to the file
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.");
            int offset = 0;
            int count = buffer.Length;

            // Writing data to the file
            fileStream.Write(buffer, offset, count);
        }
    }
}
using System;
using System.IO;

public class FileWriteExample
{
    public static void Main()
    {
        string path = "output.txt";

        // Creating a FileStream object to write data to the file
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.");
            int offset = 0;
            int count = buffer.Length;

            // Writing data to the file
            fileStream.Write(buffer, offset, count);
        }
    }
}
Imports System
Imports System.IO

Public Class FileWriteExample
	Public Shared Sub Main()
		Dim path As String = "output.txt"

		' Creating a FileStream object to write data to the file
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			Dim buffer() As Byte = System.Text.Encoding.UTF8.GetBytes("Writing data to FileStream.")
			Dim offset As Integer = 0
			Dim count As Integer = buffer.Length

			' Writing data to the file
			fileStream.Write(buffer, offset, count)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

이 코드에서는 문자열을 UTF8 인코딩을 사용하여 바이트 배열로 변환합니다. Write 메소드는 지정된 바이트 수와 오프셋으로 결정된 현재 위치에서 파일에 바이트 배열을 씁니다.

  • FileMode.Create는 동일한 이름의 기존 파일을 덮어쓰여 새 파일을 생성합니다.
  • FileAccess.Write는 FileStream에 쓰기 권한을 부여합니다.

FileStream을 사용하여 데이터 읽기

이제 FileStream을 사용하여 파일에서 데이터를 읽는 방법을 탐색해봅시다.

using System;
using System.IO;

public class FileReadExample
{
    public static void Main()
    {
        // File path
        string path = "output.txt";

        // File Stream Object
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            // Output Stream
            string output = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(output);
        }
    }
}
using System;
using System.IO;

public class FileReadExample
{
    public static void Main()
    {
        // File path
        string path = "output.txt";

        // File Stream Object
        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            // Output Stream
            string output = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(output);
        }
    }
}
Imports System
Imports System.IO

Public Class FileReadExample
	Public Shared Sub Main()
		' File path
		Dim path As String = "output.txt"

		' File Stream Object
		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
			' Output Stream
			Dim output As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(output)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

이 예시에서는 다음과 같습니다.

  • FileMode.Open은 기존 파일을 엽니다.
  • Read 메소드는 지정된 바이트 수 (버퍼 크기에 따라)를 읽고 바이트 배열 버퍼에 저장합니다.
  • 우리는 Encoding.UTF8.GetString 를 사용하여 바이트 데이터를 문자열로 다시 변환합니다.

FileStream으로 파일 접근 관리

FileStream 클래스는 파일의 접근을 제어하여 세밀한 파일 핸들 및 시스템 리소스 관리를 허용합니다. FileStream을 사용할 때, 사용 후에 스트림이 적절하게 폐기되었는지, Close() 를 수동으로 호출하거나 스트림을 자동으로 폐기하는 using 문을 사용하는 것이 중요합니다.

파일 위치 다루기

파일에서 읽기 또는 쓰기할 때마다 FileStream은 파일 내의 현재 위치를 추적합니다. 이 위치는 Position 속성을 사용하여 액세스할 수 있습니다:

fileStream.Position = 0; // Move to the beginning of the file
fileStream.Position = 0; // Move to the beginning of the file
fileStream.Position = 0 ' Move to the beginning of the file
$vbLabelText   $csharpLabel

비동기 작업을 위한 FileStream 사용

FileStream은 비동기 읽기 및 쓰기 작업에 사용될 수 있으며, 파일 작업이 수행되는 동안 다른 프로세스가 실행될 수 있도록 하여 성능을 향상시킵니다. 다음은 비동기 읽기의 기본 예입니다:

using System;
using System.IO;
using System.Threading.Tasks;

public class AsyncReadExample
{
    public static async Task Main()
    {
        // Specified Path
        string path = "output.txt";

        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length);
            string result = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(result);
        }
    }
}
using System;
using System.IO;
using System.Threading.Tasks;

public class AsyncReadExample
{
    public static async Task Main()
    {
        // Specified Path
        string path = "output.txt";

        using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length);
            string result = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine(result);
        }
    }
}
Imports System
Imports System.IO
Imports System.Threading.Tasks

Public Class AsyncReadExample
	Public Shared Async Function Main() As Task
		' Specified Path
		Dim path As String = "output.txt"

		Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, True)
			Dim buffer(1023) As Byte
			Dim bytesRead As Integer = Await fileStream.ReadAsync(buffer, 0, buffer.Length)
			Dim result As String = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)
			Console.WriteLine(result)
		End Using
	End Function
End Class
$vbLabelText   $csharpLabel

ReadAsync 메소드는 데이터를 비동기적으로 읽습니다. FileAccess.ReadFileMode.Open 매개변수는 파일이 어떻게 액세스되는지를 제어합니다.

예외 처리의 예제

FileStream을 사용할 때 예외를 적절히 처리하여 런타임 오류를 피하고 시스템 리소스를 적절히 관리하는 것이 중요합니다. 다음은 파일을 읽거나 쓸 때 예외를 처리하기 위한 패턴입니다:

using System;
using System.IO;

public class ExceptionHandlingExample
{
    public static void Main()
    {
        string path = "nonexistentfile.txt";

        try
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024];
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("Bytes Read: " + bytesRead);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"Exception: {e.Message}");
        }
    }
}
using System;
using System.IO;

public class ExceptionHandlingExample
{
    public static void Main()
    {
        string path = "nonexistentfile.txt";

        try
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[1024];
                int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                Console.WriteLine("Bytes Read: " + bytesRead);
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"Exception: {e.Message}");
        }
    }
}
Imports System
Imports System.IO

Public Class ExceptionHandlingExample
	Public Shared Sub Main()
		Dim path As String = "nonexistentfile.txt"

		Try
			Using fileStream As New FileStream(path, FileMode.Open, FileAccess.Read)
				Dim buffer(1023) As Byte
				Dim bytesRead As Integer = fileStream.Read(buffer, 0, buffer.Length)
				Console.WriteLine("Bytes Read: " & bytesRead)
			End Using
		Catch e As FileNotFoundException
			Console.WriteLine($"Exception: {e.Message}")
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

버퍼링 및 성능

FileStream 클래스에는 대용량 파일 작업 시 특히 성능을 빠르게 향상시키는 버퍼링 메커니즘이 포함되어 있습니다. 버퍼를 사용하면 데이터가 메모리에 일시적으로 저장되어, 지속적인 디스크 접근이 줄어듭니다.

using System;
using System.IO;

public class BufferingExample
{
    public static void Main()
    {
        string path = "bufferedfile.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.");

        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
        {
            fileStream.Write(data, 0, data.Length);
        }
    }
}
using System;
using System.IO;

public class BufferingExample
{
    public static void Main()
    {
        string path = "bufferedfile.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.");

        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
        {
            fileStream.Write(data, 0, data.Length);
        }
    }
}
Imports System
Imports System.IO

Public Class BufferingExample
	Public Shared Sub Main()
		Dim path As String = "bufferedfile.txt"
		Dim data() As Byte = System.Text.Encoding.UTF8.GetBytes("Buffered FileStream example.")

		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough)
			fileStream.Write(data, 0, data.Length)
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

여기서 FileOptions.WriteThrough 는 추가 버퍼링을 우회하여 데이터를 파일에 직접 쓰도록 보장합니다. 하지만 성능 조정을 위해 버퍼 크기를 제어할 수 있습니다.

IronPDF 소개합니다

FileStream C# (개발자에게 어떻게 작동하는지): 도표 1 - IronPDF: C# PDF 라이브러리

IronPDF는 .NET 응용 프로그램 내에서 PDF 문서를 생성, 편집 및 조작하기 위한 강력한 C# PDF 라이브러리입니다. 개발자는 IronPDF를 사용하여 HTML과 같은 다양한 입력에서 PDF를 생성할 수 있으며, 이미지와 심지어 원시 텍스트로도 가능합니다. 워터마킹, 병합, 분할, 비밀번호 보호와 같은 기능이 있는 IronPDF는 웹 및 데스크톱 응용 프로그램에 이상적이며 PDF 출력에 대한 정밀한 제어를 제공합니다.

IronPDF와 FileStream

여기 IronPDF를 사용하여 PDF를 생성하고 FileStream에 저장하는 예시가 있습니다. IronPDF는 FileStream과 원활하게 통합되어 개발자가 PDF 생성 및 저장을 코드로 제어할 수 있음을 보여줍니다.

using System;
using System.IO;
using IronPdf;

public class IronPDFExample
{
    public static void Main()
    {
        // Define the file path
        string path = "output.pdf";

        // Create an HTML string that we want to convert to PDF
        var htmlContent = "<h1>IronPDF Example</h1><p>This PDF was generated using IronPDF and saved with FileStream.</p>";

        // Initialize IronPDF's ChromePdfRenderer to render HTML as PDF
        var renderer = new ChromePdfRenderer();

        // Generate the PDF from the HTML string
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Use FileStream to save the generated PDF
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            pdfDocument.SaveAs(fileStream);
        }

        Console.WriteLine("PDF created and saved successfully.");
    }
}
using System;
using System.IO;
using IronPdf;

public class IronPDFExample
{
    public static void Main()
    {
        // Define the file path
        string path = "output.pdf";

        // Create an HTML string that we want to convert to PDF
        var htmlContent = "<h1>IronPDF Example</h1><p>This PDF was generated using IronPDF and saved with FileStream.</p>";

        // Initialize IronPDF's ChromePdfRenderer to render HTML as PDF
        var renderer = new ChromePdfRenderer();

        // Generate the PDF from the HTML string
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

        // Use FileStream to save the generated PDF
        using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
        {
            pdfDocument.SaveAs(fileStream);
        }

        Console.WriteLine("PDF created and saved successfully.");
    }
}
Imports System
Imports System.IO
Imports IronPdf

Public Class IronPDFExample
	Public Shared Sub Main()
		' Define the file path
		Dim path As String = "output.pdf"

		' Create an HTML string that we want to convert to PDF
		Dim htmlContent = "<h1>IronPDF Example</h1><p>This PDF was generated using IronPDF and saved with FileStream.</p>"

		' Initialize IronPDF's ChromePdfRenderer to render HTML as PDF
		Dim renderer = New ChromePdfRenderer()

		' Generate the PDF from the HTML string
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

		' Use FileStream to save the generated PDF
		Using fileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
			pdfDocument.SaveAs(fileStream)
		End Using

		Console.WriteLine("PDF created and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

결론

FileStream C# (개발자에게 어떻게 작동하는지): 도표 2 - IronPDF 라이선싱 페이지

C#의 FileStream 클래스는 파일 입출력을 관리하는 강력한 기능을 제공합니다. 개발자는 효율적으로 데이터를 읽고 쓰고, 파일 내 현재 위치를 제어하며, 비동기적으로 작업해 바이트 배열, 파일 경로, 스트림 처리가 어떻게 함께 작동하는지 이해할 수 있습니다. IronPDF와 FileStream을 함께 사용하면 .NET 응용 프로그램 내에서 PDF를 효율적으로 처리할 수 있는 유연성을 개발자에게 제공합니다. 보고서 생성, 파일 저장, 동적 콘텐츠 핸들링 여부에 상관없이 이 조합은 PDF 문서 생성 및 저장에 대한 세밀한 제어를 제공합니다.

IronPDF는 무료 체험판과 $799 라이선스 요금을 제공하여 전문적인 PDF 생성 요구에 대해 경쟁력 있는 솔루션을 제공합니다.

자주 묻는 질문

C#에서 파일 읽기와 쓰기 작업을 어떻게 수행할 수 있나요?

C#에서 FileStream 클래스를 사용하여 파일 읽기와 쓰기 작업을 수행할 수 있습니다. 이 클래스는 파일을 열고 ReadWrite 같은 메서드를 사용하여 효율적으로 파일 데이터를 처리할 수 있도록 합니다.

C#에서 파일 처리에 FileStream을 사용하는 이점은 무엇인가요?

FileStream은 바이너리 데이터 처리, 대용량 파일 관리, 비동기 파일 작업 효율화에 유용합니다. 메모리 사용을 최적화하고 파일 데이터 처리에 대한 정확한 제어를 제공합니다.

FileStream은 대용량 파일을 어떻게 처리하나요?

FileStream은 버퍼링을 사용하여 대용량 파일을 처리합니다. 이는 데이터가 메모리에 임시 저장되어 디스크 접근을 최소화하여 성능을 향상시키고 FileStream을 대용량 파일 작업에 적합하도록 만듭니다.

FileStream을 비동기 파일 작업에 사용할 수 있나요?

네, FileStream은 비동기 파일 작업을 지원합니다. ReadAsyncWriteAsync와 같은 메서드를 사용하여 동시에 처리할 수 있도록 애플리케이션 성능을 향상시킬 수 있습니다.

FileStream 객체를 적절하게 삭제하는 것이 왜 중요한가요?

FileStream 객체를 적절히 삭제하는 것은 시스템 자원을 해제하고 파일 잠금을 방지하기 위해 중요합니다. using 문을 사용하거나 Dispose 메서드를 호출하여 자원이 올바르게 해제되도록 할 수 있습니다.

C#에서 파일 처리와 PDF 생성을 어떻게 통합할 수 있나요?

C#에서 IronPDF를 사용하여 파일 처리와 PDF 생성을 통합할 수 있습니다. IronPDF를 사용하면 PDF 문서를 생성 및 조작하고 이를 FileStream을 사용하여 저장하여 파일 처리와 PDF 생성을 원활하게 결합할 수 있습니다.

IronPDF의 PDF 조작 기능은 무엇인가요?

IronPDF는 PDF 생성, 편집, 조작, 워터마크 추가, 문서 병합, 파일 분할, 암호 보호 적용 등 .NET 애플리케이션에서 포괄적인 PDF 관리를 위한 기능을 제공합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해