温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET对txt文件相关操作方法

发布时间:2021-06-29 10:27:08 来源:亿速云 阅读:257 作者:chen 栏目:开发技术

这篇文章主要介绍“ASP.NET对txt文件相关操作方法”,在日常操作中,相信很多人在ASP.NET对txt文件相关操作方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”ASP.NET对txt文件相关操作方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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")

到此,关于“ASP.NET对txt文件相关操作方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI