요약
본 문서에서는 Visual C# .NET을 사용하여 여섯 가지의 기본 파일 입/출력(I/O) 작업을 수행하는 방법에 대해 단계별로 설명합니다. .NET을 처음 사용하더라도 .NET에서 파일 작업을 하는 데 사용되는 개체 모델이 대부분의 Visual Studio 6.0 개발자에게 친숙한
FileSystemObject(FSO)와 매우 유사하다는 것을 알 수 있습니다. 사용자의 이해를 돕기 위해, 본 문서에 설명된 기능은 Microsoft 기술 자료의 다음 문서를 기초로 합니다.
- 186118 HOWTO: Use FileSystemObject with Visual Basic
.NET에서도
FileSystemObject를 계속 사용할 수 있습니다.
FileSystemObject가 구성 요소 개체 모델(COM) 구성 요소이기 때문에 .NET에서는 Interop 계층을 통해 이 개체에 액세스해야 합니다. 사용자가 이 구성 요소를 사용하려고 하면 .NET이 이 구성 요소에 대한 래퍼(wrapper)를 생성합니다. 하지만 .NET Framework의
File,
FileInfo,
Directory,
DirectoryInfo 및 기타 관련 클래스는 FSO에서 사용할 수 없는 기능을 제공하므로 Interop 계층의 오버헤드가 없습니다.
맨 위로
요구 사항
다음은 권장되는 하드웨어, 소프트웨어, 네트워크 인프라 및 필요한 서비스 팩 목록입니다.
- Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server 또는 Windows NT 4.0 Server
- Microsoft Visual Studio .NET
- Microsoft Visual Studio .NET Software Development Kit(SDK) Quickstarts
맨 위로
파일 입/출력 작업 예제
본 문서에 수록된 예제는 기본 파일 입/출력(I/O) 작업에 대해 설명합니다. "단계별 예제" 절에서는 아래의 여섯 가지 파일 입/출력 작업을 보여주는 예제 응용 프로그램을 만드는 방법에 대해 설명합니다.
- 텍스트 파일 읽기
- 텍스트 파일 쓰기
- 파일 정보 보기
- 디스크 드라이브 나열
- 폴더 나열
- 파일 나열
참고 : 다음 코드 예제를 직접 사용하려면 다음 사항에 주의하십시오.
- 아래와 같이 System.IO 네임스페이스를 포함시켜야 합니다.
using System.IO;
- 아래와 같이 winDir 변수를 선언해야 합니다.
string winDir=System.Environment.GetEnvironmentVariable("windir");
- 아래와 같이 addListItem 함수를 선언해야 합니다.
private void addListItem(string value)
{
this.listbox1.Items.Add(value);
}
참고: addListItem 함수를 선언하여 사용하는 방법 대신 다음 코드 문을 직접 사용할 수 있습니다. this.listbox1.Items.Add(value);"
맨 위로
텍스트 파일 읽기
다음 코드 예제에서는
StreamReader 클래스를 사용하여 System.ini 파일을 읽습니다. 파일 내용은
ListBox 컨트롤에 추가됩니다.
try...catch 블록은 파일이 비어 있을 경우 프로그램에 경고 메시지를 나타내는 데 사용됩니다. 파일의 끝에 도달했을 때 이를 확인하는 방법에는 여러 가지가 있지만, 이 예제에서는
Peek 메서드를 사용하여 읽기 전에 다음 줄을 검사합니다.
StreamReader reader=new StreamReader(winDir + "\\system.ini");
try
{
do
{
addListItem(reader.ReadLine());
}
while(reader.Peek() != -1);
}
catch
{
addListItem("File is empty");}
finally
{
reader.Close();
}
맨 위로
텍스트 파일 쓰기
이 코드 예제에서는
StreamWriter 클래스를 사용하여 파일을 만들고 파일에 쓰는 작업을 합니다. 기존의 파일도 같은 방법으로 열 수 있습니다.
StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
writer.WriteLine("File created using StreamWriter class.");
writer.Close();
this.listbox1.Items.Clear();
addListItem("File Written to C:\\KBTest.txt");
맨 위로
파일 정보 보기
이 코드 예제에서는
FileInfo 개체를 사용하여 파일 속성에 액세스합니다. 이 예제에서는 Notepad.exe가 사용됩니다. 파일 속성은
ListBox 컨트롤에 표시됩니다.
FileInfo FileProps =new FileInfo(winDir + "\\notepad.exe");
addListItem("File Name = " + FileProps.FullName);
addListItem("Creation Time = " + FileProps.CreationTime);
addListItem("Last Access Time = " + FileProps.LastAccessTime);
addListItem("Last Write TIme = " + FileProps.LastWriteTime);
addListItem("Size = " + FileProps.Length);
FileProps = null;
맨 위로
디스크 드라이브 나열
이 코드 예제에서는
Directory와
Drive 클래스를 사용하여 시스템의 논리 드라이브를 나열합니다. 이 예제에서 결과는
ListBox 컨트롤에 표시됩니다.
string[]drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
addListItem(drive);
}
맨 위로
하위 폴더 나열
이 코드 예제에서는
Directory 클래스의
GetDirectories 메서드를 사용하여 폴더 목록을 나열합니다.
string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
addListItem(dir);
}
맨 위로
파일 나열
이 코드 예제에서는
Directory 클래스의
GetFiles 메서드를 사용하여 파일 목록을 나열합니다.
string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
addListItem(i);
}
사용자가 파일에 액세스할 때는 여러 가지 예외가 발생할 수 있습니다. 파일이 없거나 파일이 이미 사용되고 있거나 액세스하려는 폴더의 파일에 대한 사용 권한이 없을 수 있습니다. 코드를 작성할 때는 이러한 가능성을 충분히 고려해서 생성되는 예외를 처리해야 합니다.
맨 위로
단계별 예제
- Visual C# .NET에서 새로운 Windows 응용 프로그램을 시작합니다. 기본적으로 Form1이 생성됩니다.
- Form1 코드 창을 엽니다.
- 코드 숨김 편집기에서 코드를 모두 삭제합니다.
- 코드 숨김 편집기 창에 다음 코드를 붙여넣습니다.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace fso_cs
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
string winDir=System.Environment.GetEnvironmentVariable("windir");
private System.Windows.Forms.ListBox listbox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support.
//
InitializeComponent();
//
// TO DO: Add any constructor code after InitializeComponent call.
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.listbox1 = new System.Windows.Forms.ListBox();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(216, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(216, 64);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(112, 23);
this.button2.TabIndex = 2;
this.button2.Text = "button2";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(216, 96);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(112, 23);
this.button3.TabIndex = 3;
this.button3.Text = "button3";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// listbox1
//
this.listbox1.Location = new System.Drawing.Point(24, 24);
this.listbox1.Name = "listbox1";
this.listbox1.Size = new System.Drawing.Size(176, 199);
this.listbox1.TabIndex = 0;
//
// button4
//
this.button4.Location = new System.Drawing.Point(216, 128);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(112, 23);
this.button4.TabIndex = 4;
this.button4.Text = "button4";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(216, 160);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(112, 23);
this.button5.TabIndex = 5;
this.button5.Text = "button5";
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(216, 192);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(112, 23);
this.button6.TabIndex = 6;
this.button6.Text = "button6";
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(360, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.button6,
this.button5,
this.button4,
this.button3,
this.button2,
this.button1,
this.listbox1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button6_Click(object sender, System.EventArgs e)
{
//How to obtain list of files (example uses Windows folder).
this.listbox1.Items.Clear();
string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
addListItem(i);
}
}
private void button1_Click(object sender, System.EventArgs e)
{
//How to read a text file.
//try...catch is to deal with a 0 byte file.
this.listbox1.Items.Clear();
StreamReader reader=new StreamReader(winDir + "\\system.ini");
try
{
do
{
addListItem(reader.ReadLine());
}
while(reader.Peek() != -1);
}
catch
{
addListItem("File is empty");}
finally
{
reader.Close();}
}
private void Form1_Load(object sender, System.EventArgs e)
{
this.button1.Text = "Read Text File";
this.button2.Text = "Write Text File";
this.button3.Text = "View File Information";
this.button4.Text = "List Drives";
this.button5.Text = "List Subfolders";
this.button6.Text = "List Files";
}
private void button5_Click(object sender, System.EventArgs e)
{
//How to get a list of folders (example uses Windows folder).
this.listbox1.Items.Clear();
string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
addListItem(dir);
}
}
private void button4_Click(object sender, System.EventArgs e)
{
//Demonstrates how to obtain a list of disk drives.
this.listbox1.Items.Clear();
string[]drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
addListItem(drive);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
//How to retrieve file properties (example uses Notepad.exe).
this.listbox1.Items.Clear();
FileInfo FileProps =new FileInfo(winDir + "\\notepad.exe");
addListItem("File Name = " + FileProps.FullName);
addListItem("Creation Time = " + FileProps.CreationTime);
addListItem("Last Access Time = " + FileProps.LastAccessTime);
addListItem("Last Write TIme = " + FileProps.LastWriteTime);
addListItem("Size = " + FileProps.Length);
FileProps = null;
}
private void addListItem(string value)
{
this.listbox1.Items.Add(value);
}
private void button2_Click(object sender, System.EventArgs e)
{
//Demonstrates how to create and write to a text file.
StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
writer.WriteLine("File created using StreamWriter class.");
writer.Close();
this.listbox1.Items.Clear();
addListItem("File Written to C:\\KBTest.txt");
}
}
}
- F5 키를 눌러 응용 프로그램을 빌드하고 실행합니다. 단추를 눌러 다른 동작들을 살펴봅니다. 예제 코드를 볼 때는 "Windows Form 디자이너가 생성한 코드"라는 영역을 "축소"하여 이 코드를 숨길 수 있습니다.