使用 C# 建立檔案於伺服器的方法 (ASP.NET Create File In Server)


  1. 說明
  2. 參考資料
  3. 相關連結

筆記 ASP.NET 開發如何在伺服器端進行檔案新增。

logo

說明

Namesapce

using System.IO;

程式碼

需要在應用程式資料夾中準備 uploads folder。

public ActionResult Upload(string content)
{
    string fileName = 
      string.IsNullOrEmpty(content) ? 
      "placeholder" : content;

    if (!string.IsNullOrEmpty(content))
    {
        string serverPath = 
          Path.Combine(Server.MapPath("~/uploads"), $"{content}.txt");

        using (System.IO.StreamWriter fs = 
          new System.IO.StreamWriter(serverPath))
          {
            fs.WriteLine("hello world");
          }
    }

    return File($"~/Uploads/{fileName}.txt", "text/plain");
}

參考資料

如何寫入文字檔

Multipart Internet Mail Extensions (MIME)

相關連結

ASP.NET MVC 從無到有打造一個應用系統

Visual Studio 入門教學