Visual C# を使用して基本的なファイル I/O を実行する

この記事では、Visual C# で基本的なファイル I/O を実行する方法について説明し、このタスクを実行する方法を示すコード サンプルを提供します。

元の製品バージョン: Visual C#
元の KB 番号: 304430

概要

注:

この記事では、Visual C# で 6 つの基本的なファイル入出力 (I/O) 操作を実行する方法について説明します。 .NET Frameworkを初めて使用する場合、.NET でのファイル操作のオブジェクト モデルは、多くの Visual Studio 6.0 開発者に人気のある (FSO) に似ているFileSystemObjectことがわかります。 移行を容易にするために、「 Visual Basic で FileSystemObject を使用する方法」で示されている機能。

引き続き .NET で を FileSystemObject 使用できます。 FileSystemObjectはコンポーネント オブジェクト モデル (COM) コンポーネントであるため、.NET では、相互運用機能レイヤーを介してオブジェクトにアクセスする必要があります。 コンポーネントを使用する場合は、Microsoft .NET によってコンポーネントのラッパーが生成されます。 ただし、.NET Framework内の FileDirectoryInfoFileInfoDirectory、、クラス、およびその他の関連クラスは、相互運用機能レイヤーのオーバーヘッドなしで 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;

ディスク ドライブを一覧表示する

このサンプル コードでは、 クラスと Drive クラスをDirectory使用して、システム上の論理ドライブを一覧表示します。 このサンプルでは、結果は 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);
}

ユーザーがファイルにアクセスすると、多くの問題が発生する可能性があります。 ファイルが存在しないか、ファイルが使用中であるか、ユーザーがアクセスしようとしているファイルまたはフォルダーに対する権限がない可能性があります。 コードを記述するときにこれらの可能性を考慮し、生成される可能性のある例外を処理することが重要です。

ステップ バイ ステップの例

  1. Visual C# で、新しい Windows フォーム アプリケーションを作成します。 既定では、 Form1 が作成されます。

  2. Form1 (Form1.cs) のコード ウィンドウを開きます。

  3. Form1.cs内のすべてのコードを削除します。

  4. [分離コード] ウィンドウに次のコードエディター貼り付けます。

    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);
            }
        }
    }
    
  5. Form1.Designer のコード ウィンドウを開きます。cs

  6. Form1.Designer のすべてのコードを削除します。cs

  7. 次のコードを 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;
        }
    }
    
  8. 既定では、Windows フォーム プロジェクトを作成するときに、Visual C# によって 1 つのフォームがプロジェクトに追加されます。 このフォームの名前は Form1 です。 フォームを表す 2 つのソース コード ファイルには、Form1.csForm1.Designer という名前が付けられます。csForm1.cs ファイルにコードを記述します。 Windows フォーム Designerは、Form1.Designer でデザイナーによって生成されたコードを書き込みます。cs ファイル。 前の手順のコードは、そのorganizationを反映しています。

  9. F5 キーを押してビルドし、プログラムを実行します。 ボタンをクリックして、さまざまなアクションを表示します。 サンプル コードを表示するときに、Windows フォーム Designer生成されたコードという名前の領域を折りたたんで、このコードを非表示にすることができます。