ASP. NET operations related to txt files (read write save)

  • 2021-07-06 10:41:04
  • OfStack

ASP. NET Read the contents of the txt file (Notepad):


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; 
// Get txt File stream  
namespace test 
{ 
 public partial class Text : System.Web.UI.Page 
 { 
  protected void Page_Load(object sender, EventArgs e) 
  { 
   Response.Write(GetInterIDList("asp.txt")); 
  } 
  // Read txt Contents of the file  
  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; 
  } 
 } 
}

Reading the contents of txt file is to get the file stream. Remember to reference using System. IO; .

ASP. NET Write to txt file (Notepad):


string txtPath = Server.MapPath("~\\Public\\AttInfo\\") + "Test.txt"; 
StreamWriter sw = new StreamWriter(txtPath, false, System.Text.Encoding.Default); 
sw.WriteLine("Hello World"); 
sw.WriteLine(""); // Output blank lines  
sw.WriteLine("ASP.NET Network programming  -  Script home! "); 
sw.Close();

Note: If writing to Notepad does not require a newline, you can use Write, and if you need a newline, you can use WriteLine.

ASP. NET Save the txt file (Notepad):


public void ProcessRequest(HttpContext context)
  {

   context.Response.Clear();
   context.Response.Buffer = true;
   //Server.UrlEncode  Prevent the saved file name from being garbled 
   context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(" Consumption details " + string.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + ".txt")); 
   context.Response.ContentType = "text/plain"; 
   string message = "Hello World";
   // If you want to wrap the exported file, use the Environment.NewLine
   message += "Hello World" + Environment.NewLine;
   context.Response.Write(message);
   // Stop the execution of the page   
   context.Response.End(); 
  }

Note 3 points:

1. Save the file name garbled problem: encode with Server. UrlEncode

2. Wrap problem in txt file: Environment. NewLine

3. Calls can be made with js: window. location. href= "download. ashx" or window. open ("download. ashx")

The above is about the txt file related operations, if my article is helpful to you, just like it.


Related articles: