[ASP.NET]檔案讀出顯示在網頁上時的中文變亂碼的問題

  • 15070
  • 0
  • 2010-08-02

當讀取記事本檔案,並且秀在網頁上時,讀出的中文都是亂碼

這是在藍色小舖遇到的問題,當讀取記事本檔案,並且秀在網頁上時,讀出的中文都是亂碼,請問要如何解決?

針對這個問題,最有可能的就是記事本檔案的編碼問題,一般儲存記事本檔案時,編碼預設是ANSI,而網頁內的編碼是UTF-8,最簡單的方式就是將記事本另存新檔,編碼改成UTF-8;
但若不想這麼麻煩的話,可以在讀取檔案時,透過System.Text.Encoding,在讀取檔案時,將encode設定,就可以避免這種情況

以下為程式碼

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>未命名頁面</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;
        <asp:FileUpload ID="file1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="顯示" /></div>
    </form>
</body>
</html>

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;


public partial class _Default : System.Web.UI.Page  
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button1_Click1(object sender, EventArgs e)
    {
        System.Text.Encoding encode = System.Text.Encoding.GetEncoding("big5");
        StreamReader sr = new StreamReader(file1.PostedFile.FileName, encode);
        string aLine = sr.ReadToEnd();
        Response.Write(aLine.ToString());
    }

}


執行結果

沒有設定編碼前

設定編碼後

參考

http://www.blueshop.com.tw/board/show.asp?fumcde=FUM20050124192253INM&subcde=BRD200902181416127SL#BRD20090218151832206