この記事では、Visual C# で基本的なファイル I/O を実行する方法について説明し、このタスクを実行する方法を示すコード サンプルを提供します。
元の製品バージョン: Visual C#
元の KB 番号: 304430
まとめ
Note
- この記事の 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.IO
およびSystem.Collections
について説明します。
このステップ バイ ステップの記事では、Visual C# で 6 つの基本的なファイル入出力 (I/O) 操作を実行する方法について説明します。 .NET Framework を初めて使用する場合、.NET でのファイル操作のオブジェクト モデルは、多くの Visual Studio 6.0 開発者に人気のある FileSystemObject
(FSO) に似ています。 移行を容易にするために、「 Visual Basic で FileSystemObject を使用する方法」で示されている機能。
.NET では引き続き FileSystemObject
を使用できます。 FileSystemObject
はコンポーネント オブジェクト モデル (COM) コンポーネントであるため、.NET では、相互運用レイヤーを介してオブジェクトにアクセスする必要があります。 コンポーネントを使用する場合は、コンポーネントのラッパーが Microsoft .NET によって自動的に生成されます。 ただし、.NET Framework の File
、 FileInfo
、 Directory
、 DirectoryInfo
クラス、およびその他の関連クラスは、相互運用レイヤーのオーバーヘッドなしで 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);
}
サブ フォルダーを一覧表示する
このサンプル コードでは、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# で、新しい Windows フォーム アプリケーションを作成します。 既定では、 Form1 が作成されます。
Form1 (Form1.cs) のコード ウィンドウを開きます。
Form1.cs内のすべてのコードを削除します。
次のコードを Code-Behind エディター ウィンドウに貼り付けます。
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 フォーム プロジェクトの作成時に 1 つのフォームがプロジェクトに追加されます。 このフォームの名前は Form1 です。 フォームを表す 2 つのソース コード ファイルには、 Form1.cs と Form1.Designer.csという名前が付けられています。 Form1.cs ファイルにコードを記述します。 Windows フォーム デザイナーは、デザイナーによって生成されたコードをForm1.Designer.cs ファイルに書き込みます。 前の手順のコードは、その組織を反映しています。
F5 キーを押してビルドし、プログラムを実行します。 ボタンをクリックすると、さまざまなアクションが表示されます。 サンプル コードを表示するときに、このコードを非表示にするには、 Windows フォーム デザイナーで生成されたコード という名前の領域を折りたたむ必要があります。