您的位置:首页 > 编程语言 > C#

c#如何读取txt文件内容

2014-04-11 20:59 281 查看
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.IO;

namespace test

{

public partial class Text : System.Web.UI.Page

{



//读取txt文件的内容

public string Gettext(string strfile)

{

string strout;

strout = "";

if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))

{

Console.Write("没有找到文件!");

}

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;

}

}

}

讲解一下StreamReader:

实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。

StreamReader(String, Encoding)用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。
System.Text.Encoding.Default

类型:System.Text.Encoding

操作系统的当前 ANSI 代码页的编码。

ReadToEnd从流的当前位置到末尾读取所有字符。 (重写 TextReader.ReadToEnd()。)
StreamReader(String, Encoding)用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: