ใช้วิธี WriteAllLines เพื่อเขียนอาร์เรย์ลงในไฟล์
ขั้นแรก ตั้งค่าอาร์เรย์สตริง −
string[] stringArray = new string[] {
"one",
"two",
"three"
}; ตอนนี้ ใช้วิธี WriteAllLines เพื่อเพิ่มอาร์เรย์ข้างต้นไปยังไฟล์ -
File.WriteAllLines("new.txt", stringArray); นี่คือรหัสที่สมบูรณ์ -
ตัวอย่าง
using System.IO;
using System;
public class Program {
public static void Main() {
string[] stringArray = new string[] {
"one",
"two",
"three"
};
File.WriteAllLines("new.txt", stringArray);
using (StreamReader sr = new StreamReader("new.txt")) {
string res = sr.ReadToEnd();
Console.WriteLine(res);
}
}
} ผลลัพธ์
one two three