萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 使用 StreamWriter 建立文字檔案完整範例

核心類別:StreamWriter

System.IO.StreamWriter 為字元輸出串流,支援指定編碼、自動緩衝,是 .NET 寫入文字檔最常用的類別。配合 File.CreateText 或 `new StreamWriter(path)` 即可建立/覆寫檔案。

完整 Web Forms 範例

<%@ 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>

進階用法與最佳實務

1. 指定編碼(預設 UTF-8 無 BOM)

// 明確指定 UTF-8 (含 BOM) 或 Big5 等
using (var sw = new StreamWriter(path, false, Encoding.GetEncoding("big5"))) { ... }

// 附加模式
using (var sw = new StreamWriter(path, true, Encoding.UTF8)) { ... }

2. 非同步寫入(.NET 4.5+)

public async Task WriteAsync(string path, string content)
{
    using (var sw = new StreamWriter(path, false, Encoding.UTF8))
    {
        await sw.WriteAsync(content);
    }
}

3. 寫入結構化資料(CSV/JSON)

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}");
}

常見錯誤與注意事項

  • 路徑權限:ASP.NET 執行身分(IIS_IUSRS / ApplicationPoolIdentity)需有目標資料夾寫入權限。
  • 路徑格式:使用 `@"D:\Path"` 或 `"D:\\Path"` 避免跳脫字元錯誤;伺服器端請用 `Server.MapPath("~/App_Data/file.txt")` 取得實體路徑。
  • 並發寫入:多執行緒/多請求同時寫入同一檔案會導致資料損毀,需加鎖或改用資料庫/佇列。
  • 大檔案:避免一次 `ReadAllText`/`WriteAllText` 造成記憶體壓力,改用串流分塊處理。

檔案讀取對應:StreamReader

if (File.Exists(path))
{
    using (var sr = new StreamReader(path, Encoding.UTF8))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            Response.Write(line + "
"); } } }

善用 `using` 區塊管理資源生命週期,配合適當編碼與錯誤處理,即能穩健實作檔案讀寫功能。

copyright © 萬盛學電腦網 all rights reserved