PR

【C#入門】ファイル入出力の基礎: 簡単な読み書き方法

【C#】

はじめに

C#は、Microsoftが開発した強力で柔軟なプログラミング言語です。多くのアプリケーション開発で利用されており、その範囲はデスクトップアプリケーション、Webアプリケーション、モバイルアプリケーション、ゲーム開発など多岐にわたります。今回は、C#の基本的な機能の一つであるファイル入出力について学びます。ファイル入出力は、データを永続化するために不可欠な機能であり、プログラムがファイルにデータを書き込んだり、ファイルからデータを読み込んだりするために使用されます。

ファイルの読み込み方法

ファイルの読み込みは、C#の基本的な操作の一つです。ここでは、ファイルからデータを読み込む方法について説明します。

StreamReaderを使用したファイルの読み込み

StreamReaderクラスは、テキストファイルを読み込むための便利なクラスです。以下に、StreamReaderを使用したファイルの読み込みの基本的な例を示します。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        try
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、example.txtというファイルを読み込み、各行をコンソールに出力します。usingステートメントを使用することで、StreamReaderオブジェクトが自動的に閉じられ、リソースが解放されます。

File.ReadAllLinesを使用したファイルの読み込み

File.ReadAllLinesメソッドは、ファイル全体を一度に読み込み、各行を文字列の配列として返します。この方法は、ファイルが比較的小さい場合に便利です。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        try
        {
            string[] lines = File.ReadAllLines(path);
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、ファイルを一度に読み込み、各行を配列として処理します。File.ReadAllLinesメソッドは、ファイルが大きすぎる場合にはメモリを大量に消費する可能性があるため注意が必要です。

ファイルへの書き込み方法

ファイルへの書き込みも、C#の基本的な操作の一つです。ここでは、ファイルにデータを書き込む方法について説明します。

StreamWriterを使用したファイルの書き込み

StreamWriterクラスは、テキストファイルにデータを書き込むための便利なクラスです。以下に、StreamWriterを使用したファイルの書き込みの基本的な例を示します。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        try
        {
            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("Hello, World!");
                sw.WriteLine("Welcome to C# file writing.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be written:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、example.txtというファイルにテキストを書き込みます。usingステートメントを使用することで、StreamWriterオブジェクトが自動的に閉じられ、リソースが解放されます。

File.WriteAllLinesを使用したファイルの書き込み

File.WriteAllLinesメソッドは、文字列の配列を一度にファイルに書き込みます。この方法は、複数行のテキストを一度に書き込む場合に便利です。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        string[] lines = { "Hello, World!", "Welcome to C# file writing." };

        try
        {
            File.WriteAllLines(path, lines);
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be written:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、文字列の配列をファイルに一度に書き込みます。File.WriteAllLinesメソッドは、書き込むデータが大きすぎる場合には注意が必要です。

ファイルの追記方法

ファイルにデータを追記する方法も重要です。既存のデータを保持しつつ、新しいデータを追加する方法を見てみましょう。

StreamWriterを使用したファイルの追記

StreamWriterクラスを使用してファイルにデータを追記する場合、第二引数にtrueを渡します。これにより、既存のデータを保持しながら新しいデータを追記することができます。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        try
        {
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine("This is an appended line.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be written:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、example.txtというファイルに新しい行を追記します。StreamWriterの第二引数にtrueを渡すことで、追記モードになります。

File.AppendAllLinesを使用したファイルの追記

File.AppendAllLinesメソッドは、文字列の配列をファイルに追記します。この方法は、複数行のテキストを一度に追記する場合に便利です。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        string[] lines = { "This is an appended line.", "Another appended line." };

        try
        {
            File.AppendAllLines(path, lines);
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be written:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、文字列の配列をファイルに一度に追記します。File.AppendAllLinesメソッドを使用することで、簡単にファイルにデータを追加できます。

ファイルの存在確認と削除

ファイル操作を行う前に、ファイルが存在するかどうかを確認することが重要です。また、不要になったファイルを削除する方法も学びましょう。

ファイルの存在確認

ファイルの存在を確認するには、File.Existsメソッドを使用します。このメソッドは、指定したパスにファイルが存在するかどうかをチェックし、結果をブール値で返します。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        if (File.Exists(path))
        {
            Console.WriteLine("The file exists.");
        }
        else
        {
            Console.WriteLine("The file does not exist.");
        }
    }
}

このコードは、example.txtというファイルが存在するかどうかを確認し、結果をコンソールに出力します。

ファイルの削除

ファイルを削除するには、File.Deleteメソッドを使用します。このメソッドは、指定したパスのファイルを削除します。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
                Console.WriteLine("The file has been deleted.");
            }
            else
            {
                Console.WriteLine("The file does not exist.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be deleted:");
            Console.WriteLine(e.Message);
        }
    }
}

このコードは、example.txtというファイルが存在する場合に削除し、削除の結果をコンソールに出力します。

まとめ

C#のファイル入出力は、アプリケーション開発において非常に重要な機能です。ファイルの読み込み、書き込み、追記、存在確認、削除などの基本操作をマスターすることで、データの永続化やログの管理、設定ファイルの読み書きなど、さまざまなシナリオに対応できるようになります。今回紹介した基本的な操作方法を活用して、より複雑なファイル操作に挑戦してみてください。

タイトルとURLをコピーしました