ASP.NET对txt文件相关操作(读取、写入、保存)
ASP.NET读取txt文件(记事本)内容:
usingSystem;
usingSystem.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.IO;
//获取txt文件流
namespacetest
{
publicpartialclassText:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
Response.Write(GetInterIDList("asp.txt"));
}
//读取txt文件的内容
publicstringGetInterIDList(stringstrfile)
{
stringstrout;
strout="";
if(!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))
{
}
else
{
StreamReadersr=newStreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile),System.Text.Encoding.Default);
Stringinput=sr.ReadToEnd();
sr.Close();
strout=input;
}
returnstrout;
}
}
}
读取txt文件内容就是获取文件流,记得要引用usingSystem.IO;。
ASP.NET写入txt文件(记事本):
stringtxtPath=Server.MapPath("~\\Public\\AttInfo\\")+"Test.txt";
StreamWritersw=newStreamWriter(txtPath,false,System.Text.Encoding.Default);
sw.WriteLine("HelloWorld");
sw.WriteLine("");//输出空行
sw.WriteLine("ASP.NET网络编程-毛票票!");
sw.Close();
注意:如果写入记事本不需换行,可以使用Write,需要换行的,可以使用WriteLine。
ASP.NET保存txt文件(记事本):
publicvoidProcessRequest(HttpContextcontext)
{
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";
stringmessage="HelloWorld";
//如果导出的文件要换行,用Environment.NewLine
message+="HelloWorld"+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文件的相关操作,如果我的文章对你有帮助,就点个赞吧。