国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET對txt文件相關操作(讀取、寫入、保存)

2024-07-10 12:47:45
字體:
來源:轉載
供稿:網友

ASP.NET讀取txt文件(記事本)內容:

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文件的內容   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文件內容就是獲取文件流,記得要引用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網絡編程 - 錯新站長站!"); 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("消費明細" + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".txt"));    context.Response.ContentType = "text/plain";    string message = "Hello World";   //如果導出的文件要換行,用Environment.NewLine   message += "Hello World" + Environment.NewLine;   context.Response.Write(message);   //停止頁面的執行     context.Response.End();   }

注意3點:

1.保存文件名亂碼問題:用Server.UrlEncode編碼

2.txt文件中的換行問題:Environment.NewLine

3.調用可以用js:window.location.href="download.ashx" 或window.open("download.ashx")

以上就是關于txt文件的相關操作,如果我的文章對你有幫助,就點個贊吧。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新疆| 柘荣县| 鞍山市| 社会| 灵丘县| 樟树市| 改则县| 天长市| 将乐县| 塘沽区| 阿拉善右旗| 富源县| 湛江市| 同德县| 高雄县| 乐清市| 绵竹市| 漯河市| 宁陵县| 台北县| 大石桥市| 星座| 芜湖市| 玉田县| 灯塔市| 西乌珠穆沁旗| 霍城县| 花莲市| 辉县市| 固阳县| 镇巴县| 柳州市| 罗江县| 勐海县| 竹北市| 松潘县| 沁源县| 信阳市| 汉沽区| 四平市| 罗平县|