1

I am trying to batch convert quite a number of CSV files present encoding to UTF-8 through .NET

What I have been doing till now is opening the csv file one by one and selecting "all files" from the "save as/format type" dropdown box and selecting the encoding as "UTF-8" again from the dropdown box below it and then I save it (It doesn't asks to replace the original file though).

As this procedure is quite tedious, I would like to write a tiny app for it in vb.NET

All I came up with is this: System.Text.Encoding.Convert(System.Text.Encoding.ASCII,System.Text.Encoding.UTF-8)

But thats creating an error :(

Any suggestions? Thx

UPDATE: Just updated my question to use .NET's internal lib/funcs instead of using Notepad :D

4

3 回答 3

0

看看DirectoryInfo枚举目录中的文件。

File.ReadAllText()然后看看File.WriteAllText()哪些是您可以轻松用于转换编码的便捷方法。

请注意,如果您希望在文件开头没有签名的 UTF-8 (U+FEFF),则需要使用

var encoding = new UTF8Encoding(false);
于 2012-04-25T06:18:33.297 回答
0

如果这是一次性的,请启动 PowerShell:

gci *.csv | %{ Get-Content $_ | Set-Content -Encoding UTF8 "$($_.BaseName)_Encoded.csv" }

gci *.csv :获取当前目录中的所有 csv 文件并将结果通过管道传输到“foreach”循环 (%) 每个文件的 Get-Content 然后将结果通过管道传输到执行 UTF8 转换的 Set-Content 并将结果存储在具有相同基本名称的文件,后缀为“_Encoded”。

于 2012-04-25T06:30:21.160 回答
0

试试这个Mozilla 的字符集检测器它的 .NET 端口
或者
在这里,您可以找到其他人的做法。

编辑: 或适应/使用这个

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(); 
                } 
            } 
        } 
    } 
}
于 2012-04-25T06:34:08.950 回答