方法: テキストのファイルへの書き込み

この記事では、.NET アプリ用のファイルにテキストを書き込むさまざまな方法を示します。

テキストをファイルに書き込むには、一般に次のクラスおよびメソッドを使用します。

  • StreamWriter には、同期的にファイルに書き込むメソッド (WriteWriteLine) または非同期的に書き込むメソッド (WriteAsyncWriteLineAsync) が含まれています。

  • File では、ファイルにテキストを書き込む静的メソッド (WriteAllLinesWriteAllText など)、またはファイルにテキストを追加する静的メソッド (AppendAllLinesAppendAllTextAppendText など) が提供されています。

  • Path は、ファイルまたはディレクトリのパスの情報を含む文字列用です。 これには Combine メソッドが含まれ、.NET Core 2.1 以降では Join および TryJoin メソッドが含まれています。 これらのメソッドを使用すると、ファイルまたはディレクトリ パスを作成するために文字列を連結できます。

Note

次の例では、最小限必要なコードのみを示します。 通常、実際のアプリではこれよりも信頼性の高いエラー チェックと例外処理を行います。

例:StreamWriter で同期的にテキストを書き込む

次の例では、StreamWriter クラスを使用して、新しいファイルにテキストを一度に 1 行ずつ同期的に書き込む方法を示します。 StreamWriter オブジェクトが宣言されていて、using ステートメントでインスタンス化されるため、Dispose メソッドが呼び出され、それによってストリームが自動的にフラッシュされて閉じられます。

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {

        // Create a string array with the lines of text
        string[] lines = { "First line", "Second line", "Third line" };

        // Set a variable to the Documents path.
        string docPath =
          Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the string array to a new file named "WriteLines.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt")))
        {
            foreach (string line in lines)
                outputFile.WriteLine(line);
        }
    }
}
// The example creates a file named "WriteLines.txt" with the following contents:
// First line
// Second line
// Third line
Imports System.IO

Class WriteText

    Public Shared Sub Main()

        ' Create a string array with the lines of text
        Dim lines() As String = {"First line", "Second line", "Third line"}

        ' Set a variable to the Documents path.
        Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Write the string array to a new file named "WriteLines.txt".
        Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")))
            For Each line As String In lines
                outputFile.WriteLine(line)
            Next
        End Using

    End Sub

End Class

' The example creates a file named "WriteLines.txt" with the following contents:
' First line
' Second line
' Third line

例:StreamWriter で同期的にテキストを追加する

次の例では、StreamWriter クラスを使用して、最初の例で作成したテキスト ファイルにテキストを同期的に追加する方法を示します。

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {

        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Append text to an existing file named "WriteLines.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
        {
            outputFile.WriteLine("Fourth Line");
        }
    }
}
// The example adds the following line to the contents of "WriteLines.txt":
// Fourth Line
Imports System.IO

Class AppendText

    Public Shared Sub Main()

        ' Set a variable to the Documents path.
        Dim docPath As String =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Append text to an existing file named "WriteLines.txt".
        Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")), True)
            outputFile.WriteLine("Fourth Line")
        End Using

    End Sub

End Class

' The example adds the following line to the contents of "WriteLines.txt":
' Fourth Line

例:StreamWriter で非同期的にテキストを書き込む

次の例に、 StreamWriter クラスを使用して、新しいファイルにテキストを非同期的に書き込む方法を示します。 WriteAsync メソッドを呼び出すには、async メソッド内で呼び出す必要があります。

using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the specified text asynchronously to a new file named "WriteTextAsync.txt".
        using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt")))
        {
            await outputFile.WriteAsync("This is a sentence.");
        }
    }
}
// The example creates a file named "WriteTextAsync.txt" with the following contents:
// This is a sentence.
Imports System.IO

Public Module Example
    Public Sub Main()
        WriteTextAsync()
    End Sub

    Async Sub WriteTextAsync()
        ' Set a variable to the Documents path.
        Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Write the text asynchronously to a new file named "WriteTextAsync.txt".
        Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteTextAsync.txt")))
            Await outputFile.WriteAsync("This is a sentence.")
        End Using
    End Sub
End Module

' The example creates a file named "WriteTextAsync.txt" with the following contents:
' This is a sentence.

例:File クラスを使用してテキストの書き込みと追加を行う

次の例に、 File クラスを使用して、新しいファイルにテキストを書き込み、この同じファイルに新しいテキスト行を追加する方法を示します。 WriteAllText および AppendAllLines メソッドは、ファイルを自動的に開き、閉じます。 WriteAllText メソッドに指定したパスが既に存在する場合、ファイルは上書きされます。

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Create a string with a line of text.
        string text = "First line" + Environment.NewLine;

        // Set a variable to the Documents path.
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        // Write the text to a new file named "WriteFile.txt".
        File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text);

        // Create a string array with the additional lines of text
        string[] lines = { "New line 1", "New line 2" };

        // Append new lines of text to the file
        File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines);
    }
}
// The example creates a file named "WriteFile.txt" with the contents:
// First line
// And then appends the following contents:
// New line 1
// New line 2
Imports System.IO

Class WriteFile

    Public Shared Sub Main()

        ' Create a string array with the lines of text
        Dim text As String = "First line" & Environment.NewLine

        ' Set a variable to the Documents path.
        Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

        ' Write the text to a new file named "WriteFile.txt".
        File.WriteAllText(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), text)

        ' Create a string array with the additional lines of text
        Dim lines() As String = {"New line 1", "New line 2"}

        ' Append new lines of text to the file
        File.AppendAllLines(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), lines)

    End Sub

End Class

' The example creates a file named "WriteFile.txt" with the following contents:
' First line
' And then appends the following contents:
' New line 1
' New line 2

関連項目