Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# เขียนอาร์เรย์ลงไฟล์

ใช้ File.WriteAllLines(path, string[]) เขียนอาร์เรย์สตริงลงไฟล์ ทีละบรรทัด (เพิ่ม Newline อัตโนมัติ)

ตัวอย่างโค้ด

using System;
using System.IO;

public class Program
{
    public static void Main()
    {
        string[] stringArray = { "one", "two", "three" };
        File.WriteAllLines("new.txt", stringArray);
        
        // อ่านกลับมาแสดง
        using (StreamReader sr = new StreamReader("new.txt"))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
    }
}

ผลลัพธ์

one
two
three

เมธอดที่เกี่ยวข้อง: WriteAllText (เขียนสตริงเดียว), AppendAllLines (ต่อท้ายไฟล์)