Visual C# を使用したテキスト ファイルの読み取りと書き込み

この記事は、Visual C# を使用してテキスト ファイルの読み取りと書き込みを行うのに役立ちます。

元の製品バージョン: Visual Studio
元の KB 番号: 816149

概要

この記事の「テキスト ファイルの読み取り」セクションでは、StreamReader クラスを使用してテキスト ファイルを読み取る方法について説明します。 「テキスト ファイルの書き込み (例 1)」および「テキスト ファイルの書き込み (例 2)」のセクションでは、StreamWriter クラスを使用してテキストをファイルに書き込む方法について説明します。

テキスト ファイルの読み取り

次のコードは、StreamReader クラスを使用して、テキスト ファイルを開いたり、読み取ったり、閉じたりします。 テキスト ファイルのパスを StreamReader コンストラクターに渡して、ファイルを自動的に開くことができます。 ReadLine メソッドは、テキストの各行を読み取り、読み取るときにファイル ポインターを次の行にインクリメントします。 ReadLine メソッドがファイルの末尾に達すると、null 参照が返されます。 詳細については、「StreamReader クラス」を参照してください。

  1. メモ帳でサンプル テキスト ファイルを作成します。 次の手順を実行します。

    1. hello world テキストをメモ帳に貼り付けます。
    2. ファイルを Sample.txt として保存します。
  2. Microsoft Visual Studio を起動します。

  3. [ファイル] メニューの [新規作成] をポイントし、[プロジェクト] を選択します。

  4. [プロジェクトの種類] で [Visual C# プロジェクト] を選択し、[テンプレート] で [コンソール アプリケーション] を選択します。

  5. Class1.cs ファイルの先頭に次のコードを追加します。

    using System.IO;
    
  6. Main メソッドに次のコードを追加します。

    String line;
    try
    {
        //Pass the file path and file name to the StreamReader constructor
        StreamReader sr = new StreamReader("C:\\Sample.txt");
        //Read the first line of text
        line = sr.ReadLine();
        //Continue to read until you reach end of file
        while (line != null)
        {
            //write the line to console window
            Console.WriteLine(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  7. [デバッグ] メニューで、[開始] を選択してコンパイルし、アプリケーションを実行します。 Enter キーを押して、[コンソール] ウィンドウを閉じます。 [コンソール] ウィンドウには、Sample.txt ファイルの内容が表示されます。

    Hello world
    

テキスト ファイルの書き込み (例 1)

次のコードは、StreamWriter クラスを使用して、テキストファイルを開いたり、書き込んだり、閉じたりします。 StreamReader クラスと同様に、テキスト ファイルのパスを StreamWriter コンストラクターに渡して、ファイルを自動的に開くことができます。 WriteLine メソッドは、テキストの完全な行をテキスト ファイルに書き込みます。

  1. Visual Studio を起動します。

  2. [ファイル] メニューの [新規作成] をポイントし、[プロジェクト] を選択します。

  3. [プロジェクトの種類] で [Visual C# プロジェクト] を選択し、[テンプレート] で [コンソール アプリケーション] を選択します。

  4. Class1.cs ファイルの先頭に次のコードを追加します。

    using System.IO;
    
  5. Main メソッドに次のコードを追加します。

    try
    {
        //Pass the filepath and filename to the StreamWriter Constructor
        StreamWriter sw = new StreamWriter("C:\\Test.txt");
        //Write a line of text
        sw.WriteLine("Hello World!!");
        //Write a second line of text
        sw.WriteLine("From the StreamWriter class");
        //Close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. [デバッグ] メニューで、[開始] を選択してコンパイルし、アプリケーションを実行します。 このコードは、ドライブ C に「Test.txt」という名前のファイルを作成します。メモ帳などのテキスト エディターで Test.txt を開きます。 Test.txt には、次の 2 行のテキストが含まれています。

    Hello World!!
    From the StreamWriter class
    

テキスト ファイルの書き込み (例 2)

次のコードは、StreamWriter クラスを使用して、テキストファイルを開いたり、書き込んだり、閉じたりします。 前の例とは異なり、このコードは 2 つの追加パラメーターをコンストラクターに渡します。 最初のパラメーターは、ファイルのファイル パスとファイル名です。 2 番目のパラメーター trueは、ファイルが追加モードで開かれることを指定します。 2 番目のパラメーターに false を指定すると、コードを実行するたびにファイルの内容が上書きされます。 3 番目のパラメーターは Unicode を指定するため、StreamWriter はファイルを Unicode 形式でエンコードします。 3 番目のパラメーターには、次のエンコード方法を指定することもできます。

  • ASC11
  • Unicode
  • UTF7
  • UTF8

Write メソッドは WriteLine メソッドに似ていますが、Write メソッドがキャリッジ リターンまたはライン フィード (CR/LF) 文字の組み合わせを自動的に埋め込まない点が異なります。 一度に 1 文字ずつ書き込む場合に便利です。

  1. Visual Studio を起動します。

  2. [ ファイル] メニューの [ 新規] をポイントし、[ プロジェクト] をクリックします。

  3. [プロジェクトの種類] で [Visual C# プロジェクト] をクリックし、[テンプレート] で [コンソール アプリケーション] をクリックします。

  4. Class1.cs ファイルの先頭に次のコードを追加します。

    using System.IO;
    using System.Text;
    
  5. Main メソッドに次のコードを追加します。

    Int64 x;
    try
    {
        //Open the File
        StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
    
        //Write out the numbers 1 to 10 on the same line.
        for(x=0; x < 10; x++)
        {
        sw.Write(x);
        }
    
        //close the file
        sw.Close();
    }
    catch(Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
    finally
    {
        Console.WriteLine("Executing finally block.");
    }
    
  6. [デバッグ] メニューで、[開始] を選択してコンパイルし、アプリケーションを実行します。 このコードは、ドライブ C に「Test1.txt」という名前のファイルを作成します。メモ帳などのテキスト エディターで Test1.txt を開きます。 Test1.txt には、「0123456789」という 1 行のテキストが含まれています。

テキスト ファイルの読み取り方法の完全なコード リスト

//Read a Text File
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            String line;
            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader("C:\\Sample.txt");
                //Read the first line of text
                line = sr.ReadLine();
                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the line to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                }
                //close the file
                sr.Close();
                Console.ReadLine();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

テキスト ファイルの書き込み方法の完全なコード リスト (バージョン 1)

//Write a text file - Version-1
using System;
using System.IO;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                //Pass the filepath and filename to the StreamWriter Constructor
                StreamWriter sw = new StreamWriter("C:\\Test.txt");
                //Write a line of text
                sw.WriteLine("Hello World!!");
                //Write a second line of text
                sw.WriteLine("From the StreamWriter class");
                //Close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

テキスト ファイルの書き込み方法の完全なコード リスト (バージョン 2)

//Write a text file - Version 2
using System;
using System.IO;
using System.Text;
namespace readwriteapp
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            Int64 x;
            try
            {
                //Open the File
                StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
                //Writeout the numbers 1 to 10 on the same line.
                for(x=0; x < 10; x++)
                {
                    sw.Write(x);
                }
                //close the file
                sw.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        }
    }
}

トラブルシューティング

すべてのファイル操作について、エラーと例外を処理するために、コードを try-catch-finally ブロック内に折り返すことをお勧めします。 具体的には、ファイルが無期限にロックされないように、最後のブロックでファイルのハンドルを解放することをお勧めします。 考えられるエラーには、存在しないファイル、または既に使用されているファイルが含まれます。