我正在尝试批量转换当前编码的许多CSV文件到UTF-8到.NET
到目前为止我一直在做的是逐个打开csv文件并从“另存为/格式类型”下拉框中选择“所有文件”,然后从下拉框中再次选择编码为“UTF-8”在它下面,然后我保存它(它不要求替换原始文件)。
由于这个程序非常繁琐,我想在vb.NET中为它编写一个小应用程序
我想出的就是:System.Text.Encoding.Convert(System.Text.Encoding.ASCII,System.Text.Encoding.UTF-8)
但那会造成错误:(
有什么建议吗? THX
更新:刚刚更新了我的问题,使用.NET的内部lib / func而不是使用记事本:D
答案 0 :(得分:0)
查看DirectoryInfo
以枚举目录中的文件。
然后查看File.ReadAllText()
和File.WriteAllText()
这些便于您轻松转换编码的方法。
请注意,如果您想在文件开头没有签名的UTF-8(U + FEFF),则需要使用
创建编码var encoding = new UTF8Encoding(false);
答案 1 :(得分:0)
如果这是一次性,请启动PowerShell:
gci *.csv | %{ Get-Content $_ | Set-Content -Encoding UTF8 "$($_.BaseName)_Encoded.csv" }
gci * .csv:获取当前目录中的所有csv文件,并将结果传递给“foreach”循环(%) 获取每个文件的内容,然后将结果传递给执行UTF8转换的Set-Content,并将结果存储在具有相同基本名称的文件中,后缀为“_Encoded”。
答案 2 :(得分:0)
试试this:
Mozilla's charset detector或.NET port of it
或
Here你可以找到人们做过的其他方式
修改强>
或改编/使用this
using System;
using System.Data;
using System.IO;
using System.Text;
public partial class Converting : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sourceDir = "C:\\test";
string newDir = "C:\\test2";
foreach (String sourceFile in System.IO.Directory.GetFiles(sourceDir))
{
char[] splitter = { '\\' };
String[] str = sourceFile.Split(splitter);
String fname = str[str.Length - 1];
FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.ReadWrite);
StreamReader ReadFile = new StreamReader(fs, System.Text.Encoding.ASCII);
FileStream fs1 = new FileStream(newDir +
"\\new_" + fname, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter WriteFile = new StreamWriter(fs1, System.Text.Encoding.UTF8);
String strLine;
while (ReadFile != null)
{
strLine = ReadFile.ReadLine();
//MessageBox.Show(strLine);
if (strLine != null)
{
WriteFile.WriteLine(strLine);
}
else
{
ReadFile.Close();
ReadFile = null;
WriteFile.Close();
}
}
}
}
}