ASP.NET對txt文件相關(guān)操作(讀取、寫入、保存)
ASP.NET讀取txt文件(記事本)內(nèi)容:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.IO; //獲取txt文件流 namespace test { public partial class Text : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write(GetInterIDList("asp.txt")); } //讀取txt文件的內(nèi)容 public string GetInterIDList(string strfile) { string strout; strout = ""; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile))) { } else { StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default); String input = sr.ReadToEnd(); sr.Close(); strout = input; } return strout; } } }
讀取txt文件內(nèi)容就是獲取文件流,記得要引用using System.IO;。
ASP.NET寫入txt文件(記事本):
string txtPath = Server.MapPath("~\\Public\\AttInfo\\") + "Test.txt"; StreamWriter sw = new StreamWriter(txtPath, false, System.Text.Encoding.Default); sw.WriteLine("Hello World"); sw.WriteLine(""); //輸出空行 sw.WriteLine("ASP.NET網(wǎng)絡(luò)編程 - 腳本之家!"); sw.Close();
注意:如果寫入記事本不需換行,可以使用 Write,需要換行的,可以使用 WriteLine。
ASP.NET保存txt文件(記事本):
public void ProcessRequest(HttpContext context) { context.Response.Clear(); context.Response.Buffer = true; //Server.UrlEncode 防止保存的文件名亂碼 context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode("消費(fèi)明細(xì)" + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".txt")); context.Response.ContentType = "text/plain"; string message = "Hello World"; //如果導(dǎo)出的文件要換行,用Environment.NewLine message += "Hello World" + Environment.NewLine; context.Response.Write(message); //停止頁面的執(zhí)行 context.Response.End(); }
注意3點(diǎn):
1.保存文件名亂碼問題:用Server.UrlEncode編碼
2.txt文件中的換行問題:Environment.NewLine
3.調(diào)用可以用js:window.location.href="download.ashx" 或window.open("download.ashx")
以上就是關(guān)于txt文件的相關(guān)操作,如果我的文章對你有幫助,就點(diǎn)個贊吧。
相關(guān)文章
在ASP.NET中實(shí)現(xiàn)彈出日歷的具體方法
這篇文章介紹了ASP.NET彈出日歷功能的實(shí)現(xiàn)方法,有需要的朋友可以參考一下2013-07-07Visual Studio 2017 community安裝配置方法圖文教程
這篇文章主要為大家詳細(xì)介紹了Visual Studio 2017 community安裝配置方法圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09js實(shí)現(xiàn)網(wǎng)頁防止被iframe框架嵌套及幾種location.href的區(qū)別
首先我們了解一下幾種location.href的區(qū)別簡單的說:幾種location.href的區(qū)別js實(shí)現(xiàn)網(wǎng)頁被iframe框架功能,感興趣的朋友可以了解下2013-08-08asp.net獲取ListView與gridview中當(dāng)前行的行號
這篇文章主要介紹了asp.net獲取ListView與gridview中當(dāng)前行的行號,實(shí)例分析了asp.net針對ListView與gridview獲取行號的實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-01-01