如何判断用户输入内容是否为GB2312编码格式?
如果不是,怎样强制转换为GB2312格式再保存到数据库?
js和asp.net的解决方法都行,求方法
如果不是,怎样强制转换为GB2312格式再保存到数据库?
js和asp.net的解决方法都行,求方法
解决方案 »
- jquey中 .css改变背景图片问题
- 用纯C语言开发了一个中文分词系统,速度大约1万字/1秒,大小100K(免费+开源+86万词库+操作示意图+测试用例)
- @_@ 还有比做程序员更难的事儿你知道么?
- C# WebApplication 开发监控软件的视频预览页面
- inc文件与js文件没什么区别吧!!在使用上??
- 请各位大大帮我看一下,ASP读取Access中的word文档问题
- 高分求实现这样的功能?
- 动态地绑定数据到DataGrid的两个问题?
- 如何获得前一张网页的URL?
- 怎么在asp.net添加的类中利用象messageBox一样的输出提示框?
- 不知道如何描述。。进来看下截图。
- 大家谁入到过点击查询按钮后页面刷新呢
/// <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;
}
else if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
{
targetEncoding = Encoding.Unicode;
}
else
{
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)
{
targetEncoding = Encoding.UTF8;
}
else
{
int i;
if (int.TryParse(stream.Length.ToString(), out i))
{
BinaryReader r = new BinaryReader(stream, System.Text.Encoding.Default);
byte[] ss = r.ReadBytes(i); if (IsUTF8Bytes(ss))
{
targetEncoding = Encoding.UTF8;
}
}
}
}
// 恢复Seek位置
stream.Seek(origPos, SeekOrigin.Begin);
}
return targetEncoding;
} /// <summary>
/// 判断是否是不带 BOM 的 UTF8 格式
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private static bool IsUTF8Bytes(byte[] data)
{
int charByteCounter = 1; //计算当前正分析的字符应还有的字节数
byte curByte; //当前分析的字节.
for (int i = 0; i < data.Length; i++)
{
curByte = data[i];
if (charByteCounter == 1)
{
if (curByte >= 0x80)
{
//判断当前
while (((curByte <<= 1) & 0x80) != 0)
{
charByteCounter++;
}
//标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X
if (charByteCounter == 1 || charByteCounter > 6)
{
return false;
}
}
}
else
{
//若是UTF-8 此时第一位必须为1
if ((curByte & 0xC0) != 0x80)
{
return false;
}
charByteCounter--;
}
}
if (charByteCounter > 1)
{
throw new Exception("非预期的byte格式!");
}
return true;
}