指点成金-最美分享吧

登录

c#如何读取txt文件内容

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了c#如何读取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.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 类的一个新实例。

以上是关于c#如何读取txt文件内容的主要内容,如果未能解决你的问题,请参考以下文章