通过记事本打开 CSV 文件,并在 .NET 中将其转换为 UTF-8



我正在尝试通过 .NET 将相当多的 CSV 文件编码批量转换为 UTF-8

到目前为止,我一直在做的是逐个打开csv文件,然后从"另存为/格式类型"下拉框中选择"所有文件",然后从其下方的下拉框中再次选择编码为" UTF-8",然后我保存它(它不要求替换原始文件)。

由于此过程非常繁琐,我想用 vb.NET 为它编写一个小应用程序

我想出的只是:System.Text.Encoding.Convert(System.Text.Encoding.ASCII,System.Text.Encoding.UTF-8)

但这会产生错误:(

有什么建议吗?感谢

更新

:刚刚更新了我的问题以使用.NET 的内部库/函数,而不是使用记事本:D

试试这个: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(); 
                } 
            } 
        } 
    } 
}
查看用于

枚举目录中文件的DirectoryInfo

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

请注意,如果您希望在文件开头(U + FEFF)不使用签名的UTF-8,则需要使用以下命令创建编码

var encoding = new UTF8Encoding(false);

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

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

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

最新更新