溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ASP.NET對(duì)txt文件相關(guān)操作方法

發(fā)布時(shí)間:2021-06-29 10:27:08 來源:億速云 閱讀:273 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要介紹“ASP.NET對(duì)txt文件相關(guān)操作方法”,在日常操作中,相信很多人在ASP.NET對(duì)txt文件相關(guān)操作方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”ASP.NET對(duì)txt文件相關(guān)操作方法”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

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)于“ASP.NET對(duì)txt文件相關(guān)操作方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI