프로그래밍/C#

C# .NET을 사용하여 순환적으로 디렉터리 검색

bluecandyg 2013. 7. 18. 11:10

본 문서에서는 루트 디렉터리에서 하위 디렉터리까지 순환적으로 파일을 검색하는 방법을 코드를 통해 보여줍니다. 검색 조건에 맞는 파일을 검색할 수 있도록 검색 문자열이 지정됩니다. 필요한 경우에는 코드의 각 부분에 대한 설명이 제공됩니다. 본 문서의 끝부분에는 작업 코드 예제도 수록되어 있습니다.

디렉터리 순환은 개발자에게 있어 일반적인 입/출력 작업입니다. 구성 요소 개체 모델(COM) 응용 프로그램의 경우에는 FileSystemObject를 사용하여 이 작업을 손쉽게 수행할 수 있습니다. .NET에서는 이 작업이 훨씬 더 쉬워졌습니다. FileSystemObject와 비슷하게, System.IO 이름 공간의 클래스를 사용해도 파일과 디렉터리에 개체 지향적으로 액세스할 수 있습니다.

요구 사항

  • Microsoft C# .NET 베타 2

디렉터리 순환

파일과 디렉터리 조작 클래스는 System.IO 이름 공간에 있습니다. 이 클래스를 사용하기 전에 다음 이름 공간을 프로젝트로 가져와야 합니다.

using System.IO;

System.IO 이름 공간의 클래스는 파일과 디렉터리 작업에 필요한 여러 가지 옵션을 제공합니다. System.IO 이름 공간은 인스턴스화할 수 있는 클래스뿐 아니라 파일과 디렉터리 유틸리티 클래스도 제공합니다. 이들 클래스에는 해당 유형의 변수를 선언하지 않고도 호출할 수 있는 정적 메서드가 포함되어 있습니다. 예를 들어, Directory 개체를 사용하여 주어진 디렉터리의 하위 디렉터리를 얻을 수 있습니다.

다음 코드에서는 Directory 개체의 GetDirectories라는 정적 메서드를 사용하여 문자열 배열을 반환합니다. 이 배열에는 C:\ 디렉터리의 하위 디렉터리에 대한 디렉터리 경로 이름이 포함됩니다.

string[] directories = Directory.GetDirectories("C:\\");

Directory 개체에는 특정 기준에 맞는 파일의 문자열 배열을 검색할 수 있는 GetFiles라는 메서드도 포함되어 있습니다. 다음 코드 예제에서는 File 개체를 사용하여 C:\ 디렉터리의 파일 중 확장자가 .dll인 파일을 모두 검색합니다.

string[] files = Directory.GetFiles("C:\\", "*.dll");

Directory 개체의 GetDirectoriesGetFiles 메서드만 있으면 검색 문자열에 맞는 파일을 순환적으로 검색할 수 있습니다. 다음은 순환을 수행하는 데 사용되는 방법입니다.

void DirSearch(string sDir) 
{
	try	
	{
	   foreach (string d in Directory.GetDirectories(sDir)) 
	   {
		foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
		{
		   lstFilesFound.Items.Add(f);
		}
		DirSearch(d);
	   }
	}
	catch (System.Exception excpt) 
	{
		Console.WriteLine(excpt.Message);
	}
}

위의 코드에서는 검색할 디렉터리가 포함된 문자열을 DirSearch에 전달합니다. 이 문자열 값은 검색할 디렉터리의 전체 경로 이름입니다. GetDirectories를 사용하면 프로시저에 전달되는 디렉터리의 하위 디렉터리를 검색할 수 있습니다. GetDirectories가 배열을 반환하기 때문에 for/each 문을 사용하면 각각의 하위 디렉터리를 반복해서 검색할 수 있습니다. GetFiles 메서드를 사용하면 각각의 하위 디렉터리의 파일을 반복해서 검색할 수 있습니다. 폼에서 텍스트 상자의 값은 GetFiles에 전달됩니다. 텍스트 상자에는 GetFiles에서 반환되는 결과를 필터링하는 검색 문자열이 포함됩니다. 검색 기준에 맞는 파일이 있으면 목록 상자에 추가됩니다. 들어 있는 각각의 하위 디렉터리마다 DirSearch를 다시 호출하여 하위 디렉터리에 전달합니다. 이 순환 호출을 사용하면 주어진 루트 디렉터리의 모든 하위 디렉터리를 검색할 수 있습니다.

전체 코드 예제

  1. 새 C# .NET Windows 응용 프로그램 프로젝트를 시작합니다. 기본적으로 Form1이 생성됩니다.
  2. 보기 메뉴에서 솔루션 탐색기를 표시합니다.
  3. 솔루션 탐색기에서 Form1을 마우스 오른쪽 단추로 누른 다음 코드 보기를 누릅니다.
  4. Form1 코드 창에서 기존 코드를 모두 선택한 다음 삭제합니다.
  5. Form1 코드 창에 다음 코드를 붙여넣습니다.
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    
    namespace RecursiveSearchCS
    {
        /// <summary>
        /// Summary description for Form1
        /// </summary>
        public class Form1 : System.Windows.Forms.Form
        {
            internal System.Windows.Forms.Button btnSearch;
            internal System.Windows.Forms.TextBox txtFile;
            internal System.Windows.Forms.Label lblFile;
            internal System.Windows.Forms.Label lblDirectory;
            internal System.Windows.Forms.ListBox lstFilesFound;
            internal System.Windows.Forms.ComboBox cboDirectory;
            /// <summary>
            /// Required designer variable
            /// </summary>
            private System.ComponentModel.Container components = null;
    
            public Form1()
            {
                // 
                // Required for Windows Form Designer support
                // 
                InitializeComponent();
    
                // 
                // TODO: 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.btnSearch = new System.Windows.Forms.Button();
                this.txtFile = new System.Windows.Forms.TextBox();
                this.lblFile = new System.Windows.Forms.Label();
                this.lblDirectory = new System.Windows.Forms.Label();
                this.lstFilesFound = new System.Windows.Forms.ListBox();
                this.cboDirectory = new System.Windows.Forms.ComboBox();
                this.SuspendLayout();
                // 
                // btnSearch
                // 
                this.btnSearch.Location = new System.Drawing.Point(608, 248);
                this.btnSearch.Name = "btnSearch";
                this.btnSearch.TabIndex = 0;
                this.btnSearch.Text = "Search";
                this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
                // 
                // txtFile
                // 
                this.txtFile.Location = new System.Drawing.Point(8, 40);
                this.txtFile.Name = "txtFile";
                this.txtFile.Size = new System.Drawing.Size(120, 20);
                this.txtFile.TabIndex = 4;
                this.txtFile.Text = "*.dll";
                // 
                // lblFile
                // 
                this.lblFile.Location = new System.Drawing.Point(8, 16);
                this.lblFile.Name = "lblFile";
                this.lblFile.Size = new System.Drawing.Size(144, 16);
                this.lblFile.TabIndex = 5;
                this.lblFile.Text = "Search for files containing:";
                // 
                // lblDirectory
                // 
                this.lblDirectory.Location = new System.Drawing.Point(8, 96);
                this.lblDirectory.Name = "lblDirectory";
                this.lblDirectory.Size = new System.Drawing.Size(120, 23);
                this.lblDirectory.TabIndex = 3;
                this.lblDirectory.Text = "Look In:";
                // 
                // lstFilesFound
                // 
                this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
                this.lstFilesFound.Name = "lstFilesFound";
                this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
                this.lstFilesFound.TabIndex = 1;
                // 
                // cboDirectory
                // 
                this.cboDirectory.DropDownWidth = 112;
                this.cboDirectory.Location = new System.Drawing.Point(8, 128);
                this.cboDirectory.Name = "cboDirectory";
                this.cboDirectory.Size = new System.Drawing.Size(120, 21);
                this.cboDirectory.TabIndex = 2;
                this.cboDirectory.Text = "ComboBox1";
                // 
                // Form1
                // 
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(688, 277);
                this.Controls.AddRange(new System.Windows.Forms.Control[] {
    
                this.btnSearch,
                this.txtFile,
                this.lblFile,
                this.lblDirectory,
                this.lstFilesFound,
                this.cboDirectory});
    
                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 btnSearch_Click(object sender, System.EventArgs e)
            {
                lstFilesFound.Items.Clear();
                txtFile.Enabled = false;
                cboDirectory.Enabled = false;
                btnSearch.Text = "Searching...";
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                DirSearch(cboDirectory.Text);
                btnSearch.Text = "Search";
                this.Cursor = Cursors.Default;
                txtFile.Enabled = true;
                cboDirectory.Enabled = true;
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                cboDirectory.Items.Clear();
                foreach (string s in Directory.GetLogicalDrives())
                {
                    cboDirectory.Items.Add(s);
                }
                cboDirectory.Text = "C:\\";
            }
    
            void DirSearch(string sDir) 
            {
                try	
                {
                    foreach (string d in Directory.GetDirectories(sDir)) 
                    {
                        foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
                        {
                            lstFilesFound.Items.Add(f);
                        }
                        DirSearch(d);
                    }
                }
                catch (System.Exception excpt) 
                {
                    Console.WriteLine(excpt.Message);
                }
            }
        }
    }
  6. F5 키를 눌러 예제를 빌드하고 실행합니다.

참조

자세한 내용은 다음 Microsoft 웹 사이트의 Microsoft .NET Framework SDK QuickStart 자습서를 참조하십시오.

http://www.gotdotnet.com/quickstart

자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.

306777 HOWTO: System.IO와 Visual C# .NET을 사용하여 텍스트 파일 읽기