C# 窗体 中文乱码

lin6234123456 2006-11-01 08:37:31
本人试着用C#编程,打开一文本文件显示在一文本框中,结果测试时有的文本文件正常,有的出现乱码----这些文本文件用记事本打开都是正常的,本人在网上查了好多资料,都没有解决.可能这些文本文件有多种编码,现寻找一种像记事本一样(不用选择编码)的办法(C#).分不够可再加,本人是业余爱好.
...全文
1398 38 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
38 条回复
切换为时间正序
请发表友善的回复…
发表回复
早起晚睡 2006-11-03
  • 打赏
  • 举报
回复
用UTf-8
aling9801 2006-11-03
  • 打赏
  • 举报
回复
参见另一贴子!我来接分!!
cxunjam 2006-11-02
  • 打赏
  • 举报
回复
我也有同样问题,帮忙顶啊!!!
delphi_dcs 2006-11-02
  • 打赏
  • 举报
回复
高手在哪?
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
说简单点,就是用C#设计一个类似XP自带的记事本,能打开任何(至少是我电脑上的)文本文件,不会出中文乱码.只要这样一个功能(但不能临时去选取不同的编码),解决了分不成问题.
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
UP!!
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
谢谢楼上的,我只知道这些文本文件是从电脑上随意取得(上千个文本文件会有吧),文本文件有四\五种格式,用XP自带的记事本就都不会乱码!!!我是认为C#一个这样的问题都解决不了是一种不足!(如果编程,临时去选取不同的编码,你想有多烦,而XP自带的记事本打开这些文本文件就不用选取不同的编码,一打开就正常!!)不知大家理解了我的意思!!
OrangeSeaCoast 2006-11-02
  • 打赏
  • 举报
回复
呵呵,我不高手,不过给你提个意见吧。你试试把非法的ASCII码给去掉试试,只剩下正常的字符部分。比如ASCII的1-9,11,12,12-31等等还有127以上的一些。具体查ASCII表吧。
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
高手在哪?
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
我前面多次提到,我电脑上的文本文件有四\五种格式,用XP自带的记事本就都不会乱码!!!但从网上提供的资料,都只能打开几种文本文件,其他的还是乱码.Knight94(愚翁)的BLOG我也经常去,不过这个问题怕没有深入研究?!我先去测试一下!
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
先谢楼上的,回去测试一下.下面是网上的一个资料,我试了一下没有用:
// 作者:袁晓辉
// 2005-8-8
// // // // // //
using System;
using System.Text;
using System.IO;
namespace Farproc.Text
{
/// <summary>
/// 用于取得一个文本文件的编码方式(Encoding)。
/// </summary>
public class TxtFileEncoding
{
public TxtFileEncoding()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符,Encoding.Default将被返回。
/// </summary>
/// <param name="fileName">文件名。</param>
/// <returns></returns>
public static Encoding GetEncoding(string fileName)
{
return GetEncoding(fileName, Encoding.Default);
}
/// <summary>
/// 取得一个文本文件流的编码方式。
/// </summary>
/// <param name="stream">文本文件流。</param>
/// <returns></returns>
public static Encoding GetEncoding(FileStream stream)
{
return GetEncoding(stream, Encoding.Default);
}
/// <summary>
/// 取得一个文本文件的编码方式。
/// </summary>
/// <param name="fileName">文件名。</param>
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
/// <returns></returns>
public static Encoding GetEncoding(string fileName, Encoding defaultEncoding)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
Encoding targetEncoding = GetEncoding(fs, defaultEncoding);
fs.Close();
return targetEncoding;
}
/// <summary>
/// 取得一个文本文件流的编码方式。
/// </summary>
/// <param name="stream">文本文件流。</param>
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
/// <returns></returns>
public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding)
{
Encoding targetEncoding = defaultEncoding;
if(stream != null && stream.Length >= 2)
{
//保存文件流的前4个字节
byte byte1 = 0;
byte byte2 = 0;
byte byte3 = 0;
byte byte4 = 0;
//保存当前Seek位置
long origPos = stream.Seek(0, SeekOrigin.Begin);
stream.Seek(0, SeekOrigin.Begin);

int nByte = stream.ReadByte();
byte1 = Convert.ToByte(nByte);
byte2 = Convert.ToByte(stream.ReadByte());
if(stream.Length >= 3)
{
byte3 = Convert.ToByte(stream.ReadByte());
}
if(stream.Length >= 4)
{
byte4 = Convert.ToByte(stream.ReadByte());
}
//根据文件流的前4个字节判断Encoding
//Unicode {0xFF, 0xFE};
//BE-Unicode {0xFE, 0xFF};
//UTF8 = {0xEF, 0xBB, 0xBF};
if(byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
{
targetEncoding = Encoding.BigEndianUnicode;
}
if(byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
{
targetEncoding = Encoding.Unicode;
}
if(byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
{
targetEncoding = Encoding.UTF8;
}
//恢复Seek位置
stream.Seek(origPos, SeekOrigin.Begin);
}
return targetEncoding;
}
}
}
由于在GB2312和UTF7编码都没有BOM,所以需要指定一个默认的Encoding,在找不到合法的BOM时,将返回这个

Encoding。有谁知道如何区分GB2312和UTF7编码txt文件的方法,也请告诉我。

由于只是static方法,所以不用new,直接通过类名调用方法,使用起来也很简单。

using System;
using Farproc.Text;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
string fileName = @"e:\a.txt";
//生成一个big endian Unicode编码格式的文本文件
StreamWriter sw = new StreamWriter(fileName, false, Encoding.BigEndianUnicode);//你可以试试其他编码,比如Encoding.GetEncoding("GB2312")或UTF8
sw.Write("这是一个String");
sw.Close();

//读取
Encoding fileEncoding = TxtFileEncoding.GetEncoding(fileName, Encoding.GetEncoding("GB2312"));//取得这txt文件的编码
Console.WriteLine("这个文本文件的编码为:" + fileEncoding.EncodingName);
StreamReader sr = new StreamReader(fileName, fileEncoding);//用该编码创建StreamReader

//用下面的方法虽然可以让系统自动判断文本文件的编码格式,但是我们无法取得该文本文件的编码
//sr.CurrentEncoding永远为 Unicode(UTF-8)
//StreamReader sr = new StreamReader(fileName, true);
//Console.WriteLine("这个文本文件的编码为:" + sr.CurrentEncoding.EncodingName);
Console.WriteLine("这个文本文件的内容为:" + sr.ReadToEnd());
sr.Close();
Console.ReadLine();
}
}
}

Knight94 2006-11-02
  • 打赏
  • 举报
回复
一般文本文件,常见的是以gb2312,即ASCII为单字节,中文为双字节;要么以Unicode编码,即所有字符以双字节进行存储。

相对于后者来说,在文件头加上编码标示。
那么如何判断这个表示,你可以用FileStream读出前两个字节,进行判断,例如:
byte[] bData = new byte[2];
using( FileStream fs = new FileStream( yourFileName, FileMode.Open ) )
{
fs.Read( bData, 0, 2 );
fs.Close();
}

Encoding unicode = Encoding.Unicode;

// Get the preamble for the Unicode encoder.
// In this case the preamble contains the byte order mark (BOM).
byte[] preamble = unicode.GetPreamble();

// Make sure a preamble was returned
// and is large enough to containa BOM.
if(preamble.Length >= 2)
{
if(preamble[0] == bData[0] && preamble[1] == bData[1])
{
//Read file using "unicode"
}
else
{
//Read file using "gb2312"
}
}

male110 2006-11-02
  • 打赏
  • 举报
回复

接分!
aling9801 2006-11-02
  • 打赏
  • 举报
回复
是不是没有表达清楚,要不再开个贴,只怕遇不到高手!!
aling9801 2006-11-02
  • 打赏
  • 举报
回复
帮你顶!!
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
CDSN 没有高手?
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
我试了一下我这些文本文件基本上只有三种编码(gb2312,unicode,utf8),问题是要像XP的记事本一样,可直接打开文本文件而没有乱码!!!
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
另外如果是手动的话,我自已就可以解决,关键是要像XP的记事本一样!!!
lin6234123456 2006-11-02
  • 打赏
  • 举报
回复
下面贴一个网上的记事本的代码(有改动,只保留打开文件),请大家在这基础上测试吧!关键是在OpenFile()中进行处理,不过我很怀疑不调用操作系统的底层API是否能解决问题?

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
using System.Data;

namespace 记事本
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class FormMain : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBoxEdit;
private IContainer components;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemOpen;
private System.Windows.Forms.MenuItem menuItemExit;
const int MaxLenght=2000000;

private string currentFileName;
private System.Drawing.Printing.PrintDocument printDocument=new PrintDocument();
public FormMain()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.textBoxEdit = new System.Windows.Forms.TextBox();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemOpen = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// textBoxEdit
//
this.textBoxEdit.AcceptsTab = true;
this.textBoxEdit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.textBoxEdit.Cursor = System.Windows.Forms.Cursors.Arrow;
this.textBoxEdit.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBoxEdit.Location = new System.Drawing.Point(0, 0);
this.textBoxEdit.MaxLength = 2000000;
this.textBoxEdit.Multiline = true;
this.textBoxEdit.Name = "textBoxEdit";
this.textBoxEdit.ReadOnly = true;
this.textBoxEdit.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxEdit.Size = new System.Drawing.Size(442, 393);
this.textBoxEdit.TabIndex = 0;
this.textBoxEdit.WordWrap = false;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemOpen,
this.menuItemExit});
this.menuItemFile.Text = "文件(&F)";
//
// menuItemOpen
//
this.menuItemOpen.Index = 0;
this.menuItemOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.menuItemOpen.Text = "打开(O)...";
this.menuItemOpen.Click += new System.EventHandler(this.menuItem5_Click);
//
// menuItemExit
//
this.menuItemExit.Index = 1;
this.menuItemExit.Text = "退出(&X)";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// FormMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(442, 393);
this.Controls.Add(this.textBoxEdit);
this.Menu = this.mainMenu1;
this.Name = "FormMain";
this.Text = "TEST";
this.ResumeLayout(false);
this.PerformLayout();

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new FormMain());
}
private void menuItem5_Click(object sender, System.EventArgs e)
{

string file=GetOpenFile();
if(file==null)
{
return;
}
else
{
currentFileName=file;
OpenFile();
}
}
private void OpenFile()
{
try
{
FileInfo f=new FileInfo(currentFileName);
StreamReader reader=f.OpenText();
textBoxEdit.Text=reader.ReadToEnd();
reader.Close();
this.Text="显示--"+f.Name;
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
private string GetOpenFile()
{
OpenFileDialog openFile=new OpenFileDialog();
openFile.Title="TEST";
openFile.CheckFileExists=true;
openFile.CheckPathExists=true;
openFile.AddExtension=true;
openFile.Multiselect=false;
openFile.Filter="文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
if(openFile.ShowDialog()==DialogResult.OK)
{
return openFile.FileName;
}
else
{
return null;
}
}
private void menuItemExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
江海汇 2006-11-02
  • 打赏
  • 举报
回复
先了解一下编码知识, 就不难了. 要判断它属于哪知编码, 然后再用该编码方式打开, 不能一刀切.
加载更多回复(18)

111,092

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧