使用Stream 数据流实现文档编码转换

因学习需要,有时自己要从一堆TXT文档中找代码,如果直接合并会有些编码不同出现乱码。

所以自己试着做了一个小程序,可以自动识别文档编码并转换 或 合并功能。

功能较为简单,但是很实用,所以现在放出来分享一下:

链接:https://pan.baidu.com/s/1NxypJhL9iwpMCfTstGNs8w
提取码:4dvv

 

以下是 源代码,转码部分也是抄别人的:

{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) //文件夹浏览器
{
textBox2.Text = folderBrowserDialog1.SelectedPath; //获得 文件夹浏览控件 的选择路径
button4.PerformClick();
}
}
private void button4_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
if (Directory.Exists(textBox2.Text)) //判断目录是否存在
{
DirectoryInfo info = new DirectoryInfo(textBox2.Text);
path = textBox2.Text;
FileInfo[] files = info.GetFiles("*.txt"); //匹配 TXT文件格式
//string[] extensions = new[] { ".txt", ".ini" }; //创建数组 用来过滤多文件格式
//FileInfo[] files =
// info.GetFiles()
// .Where(f => extensions.Contains(f.Extension.ToLower()))
// .ToArray();
foreach (var i in files)
{
listBox1.Items.Add(i);
}
}
else
{
MessageBox.Show("目录不存在!");
}
}
string path;
string savepath;
private void button5_Click(object sender, EventArgs e)
{
Encoding encoding = new UTF8Encoding(false);
if (radioButton2.Checked)
{
encoding = Encoding.GetEncoding("gbk");
}
if (checkBox1.Checked == true)
{
savepath = path;
}
else
{
savepath = textBox3.Text;
}
if (listBox1.Items.Count > 0)
{
if (Directory.Exists(savepath))
{
try
{
string str = "";
foreach (var i in listBox1.Items)
{
using (StreamReader reader = new StreamReader(path + @"\" + i, EncodingType.GetType(path + @"\" + i)))
{
str = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter(savepath + @"\" + i, false, encoding))
{
writer.WriteLine(str);
}
}
MessageBox.Show("转换编码成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
else
{
MessageBox.Show("保存目录不存在!");
}
}
else
{
MessageBox.Show("没有可以转换的文件!");
}
}
private void button6_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) //文件夹浏览器
{
textBox3.Text = folderBrowserDialog1.SelectedPath; //获得 文件夹浏览控件 的选择路径
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
textBox3.ReadOnly = true;
textBox3.Text = "";
button6.Enabled = false;
}
else
{
textBox3.ReadOnly = false;
button6.Enabled = true;
}
}
private void button1_Click_1(object sender, EventArgs e)
{
if (listBox1.Items.Count > 1)
{
saveFileDialog1.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //设置保存文件的格式
saveFileDialog1.FileName = "-文档合并-";
saveFileDialog1.InitialDirectory = path;
if (saveFileDialog1.ShowDialog() == DialogResult.OK) //模态显示 保存文件控件
{
try
{
string str = "";
string title = "";
using (StreamWriter reset = new StreamWriter(saveFileDialog1.FileName, false))
{
reset.Write(str);
}
if (checkBox2.Checked == true)
{
foreach (var i in listBox1.Items)
{
using (StreamReader reader = new StreamReader(path + @"\" + i, EncodingType.GetType(path + @"\" + i)))
{
str = reader.ReadToEnd();
title = "\r//+++++" + i + "+++++//\r\r";
}
if (str.Trim() != "")
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName, true))
{
writer.WriteLine(title + str);
}
}
}
}
else
{
foreach (var i in listBox1.Items)
{
using (StreamReader reader = new StreamReader(path + @"\" + i, EncodingType.GetType(path + @"\" + i)))
{
str = reader.ReadToEnd();
}
if (str.Trim() != "")
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName, true))
{
writer.WriteLine(str);
}
}
}
}
MessageBox.Show("合并完成!");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
}
}
else
{
MessageBox.Show("没有可以合并的文件!");
}
}
}
}

//////////////////////////转码部分/////////////////////////////////////////


{
public class EncodingType
{
/// <summary>
/// 给定文件的路径,读取文件的二进制数据,判断文件的编码类型
/// </summary>
/// <param name=“FILE_NAME“>文件路径</param>
/// <returns>文件的编码类型</returns>
public static System.Text.Encoding GetType(string FILE_NAME) //使用静态方法 调用时无需实例化,占用一块固定内存
{
FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
Encoding r = GetType(fs);
fs.Close();
return r;
}

/// <summary>
/// 通过给定的文件流,判断文件的编码类型
/// </summary>
/// <param name=“fs“>文件流</param>
/// <returns>文件的编码类型</returns>
public static System.Text.Encoding GetType(FileStream fs)
{
byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM
Encoding reVal = Encoding.Default;

BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
int i;
int.TryParse(fs.Length.ToString(), out i);
byte[] ss = r.ReadBytes(i);
if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
{
reVal = Encoding.UTF8;
}
else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
{
reVal = Encoding.BigEndianUnicode;
}
else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
{
reVal = Encoding.Unicode;
}
r.Close();
return reVal;

}

/// <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;
}

}
}

 

posted @ 2020-05-04 17:34  Bing-yang  阅读(618)  评论(0)    收藏  举报