1. 程式人生 > >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:

實現一個 ,使其以一種特定的編碼從位元組流中讀取字元。


System.Text.Encoding.Default
型別:System.Text.Encoding
作業系統的當前 ANSI 內碼表的編碼。