Visual C#을 사용하여 기본 파일 I/O 수행
이 문서에서는 Visual C#에서 기본 파일 I/O를 수행하는 방법을 설명하고 이 작업을 수행하는 방법을 보여 주는 코드 샘플을 제공합니다.
원래 제품 버전: Visual C#
원본 KB 번호: 304430
요약
참고
- 이 문서의 Visual Basic .NET 버전은 Visual Basic 2005 또는 Visual Basic .NET에서 기본 파일 I/O를 수행하는 방법을 참조하세요.
- 이 문서의 Visual C++ .NET 버전은 Visual C++ 또는 Visual C++ .NET에서 기본 파일 I/O를 수행하는 방법을 참조하세요.
- 이 문서에서는 Microsoft .NET Framework 클래스 라이브러리 네임스페이스 및
System.Collections
를 참조합니다System.IO
.
이 단계별 문서에서는 Visual C#에서 6가지 기본 파일 입력/출력(I/O) 작업을 수행하는 방법을 보여 줍니다. .NET Framework 사용하는 경우 .NET의 파일 작업에 대한 개체 모델이 많은 Visual Studio 6.0 개발자에게 FileSystemObject
널리 사용되는 FSO(FSO)와 비슷하다는 것을 알게 됩니다. 더 쉽게 전환할 수 있도록 Visual Basic에서 FileSystemObject를 사용하는 방법에 설명된 기능을 제공합니다.
.NET에서 을 FileSystemObject
계속 사용할 수 있습니다. 는 FileSystemObject
COM(구성 요소 개체 모델) 구성 요소이므로 .NET을 사용하려면 개체에 대한 액세스가 Interop 계층을 통해 있어야 합니다. Microsoft .NET은 구성 요소를 사용하려는 경우 구성 요소에 대한 래퍼를 생성합니다. 그러나 File
.NET Framework , FileInfo
, , Directory
DirectoryInfo
클래스 및 기타 관련 클래스는 Interop 계층의 오버헤드 없이 FSO에서 사용할 수 없는 기능을 제공합니다.
설명된 파일 I/O 작업
이 문서의 예제에서는 기본 파일 I/O 작업을 설명합니다. 단계별 예제 섹션에서는 다음 파일 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);
}
하위 폴더 나열
이 샘플 코드는 클래스의 GetDirectories
메서드를 Directory
사용하여 폴더 목록을 가져옵니다.
string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
addListItem(dir);
}
파일 나열
이 샘플 코드는 클래스의 GetFiles
메서드를 Directory
사용하여 파일 목록을 가져옵니다.
string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
addListItem(i);
}
사용자가 파일에 대한 액세스 권한을 얻을 때 많은 문제가 발생할 수 있습니다. 파일이 없거나, 파일이 사용 중이거나, 사용자가 액세스하려는 파일 또는 폴더에 대한 권한이 없을 수 있습니다. 코드를 작성할 때 이러한 가능성을 고려하고 생성될 수 있는 예외를 처리하는 것이 중요합니다.
단계별 예제
Visual C#에서 새 Windows Forms 애플리케이션을 만듭니다. 기본적으로 Form1 이 만들어집니다.
Form1(Form1.cs)에 대한 코드 창을 엽니다.
Form1.cs 모든 코드를 삭제합니다.
코드 숨김 편집기 창에 다음 코드를 붙여넣습니다.
using System.Windows.Forms; using System.IO; namespace fso_cs { public partial class Form1 : Form { string winDir = System.Environment.GetEnvironmentVariable("windir"); public Form1() { InitializeComponent(); } 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 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"); } 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 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 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 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 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 addListItem(string value) { this.listBox1.Items.Add(value); } } }
Form1.Designer 대한 코드 창을 엽니다. cs.
Form1.Designer 모든 코드를 삭제합니다. cs.
Form1.Designer 다음 코드를 붙여넣습니다. cs.
namespace fso_cs { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (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.button4 = new System.Windows.Forms.Button(); this.button5 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // button1 this.button1.Location = new System.Drawing.Point(53, 30); 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(53, 62); 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(53, 94); 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); // button4 this.button4.Location = new System.Drawing.Point(53, 126); 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(53, 158); 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(53, 190); 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); // listBox1 this.listBox1.FormattingEnabled = true; this.listBox1.Location = new System.Drawing.Point(204, 30); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(270, 199); this.listBox1.TabIndex = 7; // Form1 this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(525, 273); this.Controls.Add(this.button6); this.Controls.Add(this.button5); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.listBox1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion 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; private System.Windows.Forms.ListBox listBox1; } }
기본적으로 Visual C#은 Windows Forms 프로젝트를 만들 때 하나의 폼을 프로젝트에 추가합니다. 이 양식의 이름은 Form1입니다. 양식을 나타내는 두 소스 코드 파일의 이름은 Form1.cs 및 Form1.Designer. cs. Form1.cs 파일에 코드를 작성합니다. Windows Forms Designer Form1.Designer 디자이너 생성 코드를 작성합니다. cs 파일입니다. 이전 단계의 코드는 해당 organization 반영합니다.
F5 키를 눌러 프로그램을 빌드한 다음 실행합니다. 단추를 클릭하여 다른 작업을 봅니다. 샘플 코드를 볼 때 Windows Form Designer 생성된 코드라는 영역을 축소하여 이 코드를 숨기는 것이 좋습니다.
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기