关于理论资料可查看:
 
 
InBlock.gif
public
static Encoding GetFileEncoding(
string filePath)
InBlock.gif                {
InBlock.gif                        Encoding encoding =
null;
InBlock.gif                        FileStream fStream = File.Open(filePath, FileMode.Open);
InBlock.gif                        
if (fStream.CanSeek)
InBlock.gif                        {
InBlock.gif                                
byte[] data =
new
byte[4];
InBlock.gif                                fStream.Read(data, 0, 4);
InBlock.gif
InBlock.gif                                
int markerLength = 0;
InBlock.gif                                
switch (data[0])
InBlock.gif                                {
InBlock.gif                                        
case 0xef:
// UTF8
InBlock.gif                                                markerLength = 3;
InBlock.gif                                                
if (data.Length < 3)
InBlock.gif                                                        
break;
InBlock.gif                                                
if (data[1] == 0xbb && data[2] == 0xbf)
InBlock.gif                                                        encoding = Encoding.UTF8;
InBlock.gif                                                
break;
InBlock.gif                                        
case 0xfe:
// UTF 16 BE
InBlock.gif                                                markerLength = 2;
InBlock.gif                                                
if (data[1] == 0xff)
InBlock.gif                                                        encoding = Encoding.BigEndianUnicode;
InBlock.gif                                                
break;
InBlock.gif                                        
case 0xff:
// UTF 16 LE
InBlock.gif                                                markerLength = 2;
InBlock.gif                                                
if (data[1] == 0xfe)
InBlock.gif                                                        encoding = Encoding.Unicode;
InBlock.gif                                                
break;
InBlock.gif                                        
default:
InBlock.gif                                                encoding = Encoding.ASCII;
InBlock.gif                                                
break;
InBlock.gif                                }
InBlock.gif                        }
InBlock.gif
InBlock.gif                        fStream.Dispose();
InBlock.gif                        fStream.Close();
InBlock.gif                        fStream =
null;
InBlock.gif                        
return encoding;
InBlock.gif                }