用如下的方式获得文件内容 StreamReader sr = new StreamReader( yourFileName, Encoding.Default ); or StreamReader sr = new StreamReader( yourFileName, Encoding.GetEncoding( "gb2312" ) );
用如下的方式获得文件内容 StreamReader sr = new StreamReader( yourFileName, Encoding.Default ); or StreamReader sr = new StreamReader( yourFileName, Encoding.GetEncoding( "gb2312" ) );这些方法我也知道(类似的还有几个),但都只能打开几种文本文件,其他的还是乱码,
一般文本文件,常见的是以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 (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" } }
StreamReader sr = new StreamReader( yourFileName, Encoding.Default );
or
StreamReader sr = new StreamReader( yourFileName, Encoding.GetEncoding( "gb2312" ) );
StreamReader sr = new StreamReader( yourFileName, Encoding.Default );
or
StreamReader sr = new StreamReader( yourFileName, Encoding.GetEncoding( "gb2312" ) );这些方法我也知道(类似的还有几个),但都只能打开几种文本文件,其他的还是乱码,
功能齐全记事本:
http://download.csdn.net/html/2006-10/30/159738.html
功能齐全记事本:
http://download.csdn.net/html/2006-10/30/159738.html
试了一下,还是乱码,类似记事本试用过几个,但问题同样,XP自带的记事本说不定不是用C#编得!
继续顶,反正有的是分(我留着也没用,本人公务员(兵)一个)
乱码肯定是有原因的,除非你的txt文件里面有多种不同的字符。
那么如何判断这个表示,你可以用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 (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"
}
}
// 作者:袁晓辉
// 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();
}
}
}
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();
}
}
}