System.IO.StreamWriter 為字元輸出串流,支援指定編碼、自動緩衝,是 .NET 寫入文字檔最常用的類別。配合 File.CreateText 或 `new StreamWriter(path)` 即可建立/覆寫檔案。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
private const string FILE_PATH = @"D:\MyFile.txt";
protected void Page_Load(object sender, EventArgs e)
{
WriteFile(FILE_PATH);
}
private void WriteFile(string path)
{
if (File.Exists(path))
{
Response.Write($"檔案已存在:{path}
");
return;
}
// using 確保自動關閉與釋放資源
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("這是我的第一個程式。");
sw.WriteLine("作者:範例程式");
sw.WriteLine($"建立時間:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
Response.Write("檔案建立完成!
");
}
</script>
<html><body><form runat="server"></form></body></html>
// 明確指定 UTF-8 (含 BOM) 或 Big5 等
using (var sw = new StreamWriter(path, false, Encoding.GetEncoding("big5"))) { ... }
// 附加模式
using (var sw = new StreamWriter(path, true, Encoding.UTF8)) { ... }
public async Task WriteAsync(string path, string content)
{
using (var sw = new StreamWriter(path, false, Encoding.UTF8))
{
await sw.WriteAsync(content);
}
}
var users = new[] { new { Id = 1, Name = "張三" }, new { Id = 2, Name = "李四" } };
using (var sw = new StreamWriter("users.csv"))
{
sw.WriteLine("Id,Name");
foreach (var u in users) sw.WriteLine($"{u.Id},{u.Name}");
}
if (File.Exists(path))
{
using (var sr = new StreamReader(path, Encoding.UTF8))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Response.Write(line + "
");
}
}
}
善用 `using` 區塊管理資源生命週期,配合適當編碼與錯誤處理,即能穩健實作檔案讀寫功能。