ตั้งค่าอาร์เรย์สตริงสำหรับค่า -
string[] names = new string[] {"Jack", "Tom"}; ตอนนี้ใช้อาร์เรย์ foreach เขียนเนื้อหาในไฟล์ -
using (StreamWriter sw = new StreamWriter("names.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
} ต่อไปนี้คือตัวอย่างที่แสดงอาร์เรย์ของสตรีมเพื่อเขียนข้อความไปยังไฟล์ -
ตัวอย่าง
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
string[] names = new string[] {"Jack", "Tom"};
using (StreamWriter sw = new StreamWriter("names.txt")) {
foreach (string s in names) {
sw.WriteLine(s);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("names.txt")) {
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}