今天想把几部小说导入手机,用的是goodReader,不支持ANSI,可是电脑上默认的格式都是ansi,于是得修改成utf8的。最简单的方法是记事本打开,另存为,
编码改成utf8。方法简单,但是要改的文件多,实在麻烦。于是自己动手写个批量转换的。
using System;
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ansi2utf8
{
public partial class Form1 : Form
{
string tips;
DirectoryInfo dirInfo;
FileInfo[] fileInfo;
public Form1()
{
InitializeComponent();
}
//设置目录
public void setDirInfo(string path)
{
this.dirInfo = new DirectoryInfo(path);
}
//得到目录下的所有文本文件
private void getFileInfos()
{
if (this.dirInfo != null)
{
this.fileInfo = this.dirInfo.GetFiles("*.txt", SearchOption.AllDirectories);
}
else
{
this.tips = "没找到txt文件";
}
}
//转换
public void Transform()
{
try
{
this.getFileInfos();
foreach (FileInfo fi in this.fileInfo)
{
FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
StreamReader streamReader = new StreamReader(fs,Encoding.Default);
//label3.Text = streamReader.ReadLine();
string tmpFileName = fi.FullName + ".txt";
string currentFileName = fi.FullName;
File.WriteAllText(tmpFileName, streamReader.ReadToEnd(), Encoding.UTF8);
streamReader.Close();
File.Delete(currentFileName);
//File.Move(currentFileName, tmpFileName);
File.Move(tmpFileName, currentFileName);
}
this.tips = "转换完毕";
}
catch (Exception ex)
{
this.tips = "sorry,出错了:"+ex.Message;
}
}
//文件浏览按钮
private void button1_Click(object sender, EventArgs e)
{
folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyComputer;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath.ToString();
}
}
//开始转换
private void button2_Click(object sender, EventArgs e)
{
setDirInfo(textBox1.Text);
Transform();
label2.Text = tips;
}
}
}
之中遇到的一个关键问题---存储时覆盖原文件总给我提示“另一个进程在调用它”,后来只好先另存为,再move了·····不晓得有没有更好的办法。