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

首頁 > 編程 > .NET > 正文

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

2024-07-10 13:29:24
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了ASP.NETtxt文件相關操作,包括讀取、寫入、保存,需要的朋友可以參考下

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

 

 
  1. using System;  
  2. using System.Collections;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.HtmlControls;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.WebControls.WebParts;  
  11. using System.IO;  
  12. //獲取txt文件流  
  13. namespace test  
  14. {  
  15. public partial class Text : System.Web.UI.Page  
  16. {  
  17. protected void Page_Load(object sender, EventArgs e)  
  18. {  
  19. Response.Write(GetInterIDList("asp.txt"));  
  20. }  
  21. //讀取txt文件的內容  
  22. public string GetInterIDList(string strfile)  
  23. {  
  24. string strout;  
  25. strout = "";  
  26. if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))  
  27. {  
  28. }  
  29. else 
  30. {  
  31. StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default);  
  32. String input = sr.ReadToEnd();  
  33. sr.Close();  
  34. strout = input;  
  35. }  
  36. return strout;  
  37. }  
  38. }  

讀取txt文件內容就是獲取文件流,記得要引用using System.IO;。

ASP.NET寫入txt文件(記事本):

 

 
  1. string txtPath = Server.MapPath("~//Public//AttInfo//") + "Test.txt";  
  2. StreamWriter sw = new StreamWriter(txtPath, false, System.Text.Encoding.Default);  
  3. sw.WriteLine("Hello World");  
  4. sw.WriteLine(""); //輸出空行  
  5. sw.WriteLine("ASP.NET網絡編程 - 武林網!");  
  6. sw.Close(); 

注意:如果寫入記事本不需換行,可以使用 Write,需要換行的,可以使用 WriteLine。

ASP.NET保存txt文件(記事本):

 

 
  1. public void ProcessRequest(HttpContext context) 
  2.  
  3. context.Response.Clear(); 
  4. context.Response.Buffer = true
  5. //Server.UrlEncode 防止保存的文件名亂碼 
  6. context.Response.AddHeader("Content-Disposition""attachment;filename=" + context.Server.UrlEncode("消費明細" + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".txt"));  
  7. context.Response.ContentType = "text/plain";  
  8. string message = "Hello World"
  9. //如果導出的文件要換行,用Environment.NewLine 
  10. message += "Hello World" + Environment.NewLine; 
  11. context.Response.Write(message); 
  12. //停止頁面的執行  
  13. context.Response.End();  

注意3點:

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

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

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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 连州市| 德昌县| 白城市| 唐河县| 育儿| 论坛| 锦屏县| 衡阳县| 罗定市| 香港| 阿合奇县| 潼关县| 平泉县| 枞阳县| 龙川县| 垦利县| 庐江县| 义乌市| 苏尼特右旗| 韶关市| 东丰县| 博湖县| 洪雅县| 凤阳县| 陆川县| 昌都县| 杭锦旗| 溆浦县| 嘉峪关市| 伊川县| 界首市| 新昌县| 潮州市| 雷州市| 额济纳旗| 和田市| 东海县| 三亚市| 大英县| 玛纳斯县| 彩票|