c#如何读取txt文件内容

来源:互联网 发布:淘宝秒杀作弊器 编辑:程序博客网 时间:2024/05/20 09:48

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 类的一个新实例。
1 0