1. 程式人生 > 實用技巧 >.net core 匯出檔案到瀏覽器

.net core 匯出檔案到瀏覽器

        public IActionResult ExportCod3es(string codes)
        {
            try
            {
                byte[] bs = { };
                if (string.IsNullOrEmpty(codes))
                    return File(bs, "text/xml", "匯出出錯.txt");

                var filename = DateTime.Now.ToString("yyyyMMddHHmmss
") + $"PC退貨.txt"; using (MemoryStream mem = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(mem)) { sw.BaseStream.Seek(0, SeekOrigin.End); var list = codes.Split(',
').ToList(); //開始寫入 foreach (var item in list) { sw.WriteLine(item); } //清空緩衝區 sw.Flush(); //關閉流 sw.Close(); }
return File(mem.ToArray(), "text/xml", filename); } } catch (Exception ex) { byte[] bs = { }; return File(bs, "text/xml", "匯出出錯.txt"); } }

參考:https://www.cnblogs.com/ShenJA/p/12580622.html