[C#] Writing Array Data to a Text File (File.WriteAllLines)

To save a “string array” or “list” directly to a file, using the WriteAllLines method in the System.IO.File class is the most efficient way. By using this method, you do not need to write a loop with StreamWriter; you can complete the data export in just one line.

目次

Implementation Sample: Saving a Shopping Memo

The following code creates and saves a “shopping list” stored in an array as a text file (Memo.txt).

Sample Code

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        // 1. Create data to write (string array)
        string[] shoppingList = new string[]
        {
            "Milk 1 pack",
            "Bread 6 slices",
            "Eggs 10 count",
            "Laundry detergent refill"
        };

        // File name to save
        string filePath = "Memo.txt";

        try
        {
            Console.WriteLine("Exporting file...");

            // 2. Write all array contents to the file at once
            // File.WriteAllLines(file path, array)
            // *If the specified file already exists, it will be overwritten.
            File.WriteAllLines(filePath, shoppingList);

            Console.WriteLine("Save completed.");

            // (For confirmation) Read and display the saved content
            Console.WriteLine("\n--- Contents of Memo.txt ---");
            string content = File.ReadAllText(filePath);
            Console.WriteLine(content);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred during writing: " + ex.Message);
        }
    }
}

Execution Result

Exporting file...
Save completed.

--- Contents of Memo.txt ---
Milk 1 pack
Bread 6 slices
Eggs 10 count
Laundry detergent refill

Explanation and Benefits

The File.WriteAllLines method automatically performs the following processes internally:

  • Opens the file in create (or overwrite) mode.
  • Writes each element of the array one by one and adds a line break at the end of each line.
  • Closes the file and releases resources.

This prevents errors caused by forgetting to close a file. It also reduces the amount of code and significantly improves readability. This is a basic technique that can be used in various situations, such as outputting log dumps or saving simple list data.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次