
弄了一个文本读写修改器,但是运行程序更改之后一直存在中文乱码问题,用 NOTEpad++ 打开显示是 但是用 Encoding.Default,Encoding.GetEncoding("uft-8"),Encoding.GetEncoding("")都试过了,但是都不行,麻烦各位指点一二。
代码,贴上 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO;
namespace frmModify { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private List<string> lines;</string>
private void label3_Click(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } private void btnSelect_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtPath.Text = dialog.SelectedPath; } } private void btnModify_Click(object sender, EventArgs e) { if(txtPath.Text == string.Empty) { MessageBox.Show("请选择文件"); return; } string[] files = System.IO.Directory.GetFiles(txtPath.Text, "*.xml", SearchOption.AllDirectories); foreach(string file in files) { LoadFile(file); ReplaceText(); SaveFile(file); } MessageBox.Show("替换成功"); } private void LoadFile(string file) { lines = System.IO.File.ReadAllLines(file).ToList(); } private void SaveFile(string file) { System.IO.File.SetAttributes(file, FileAttributes.Normal); System.IO.File.WriteAllLines(file, lines, Encoding.GetEncoding("")); } private void ReplaceText() { foreach (string line in lines) { if (line.IndexOf("删除单据") > 0) { line.Replace("Type=\"Edit\"", "Type=\"Print\""); } } } } }]
1 GDC 2018-12-22 13:14:02 +08:00 via iPhone 只要不超出编码范围的字符,无论存什么编码,打开的时候编码对应,就不会出现乱码。 同理,C# 在打开你现有文件的时候,也要指定一致的编码,不然它读到的就是乱码了,保存之后当然也是乱码。 |
2 imn1 2018-12-22 13:34:33 +08:00 同上,没看到读入时编码的判断,也没看到转码的操作 单纯读入就指定一个编码写入? 建议养成良好习惯,少用"",windows 改用 CP936,linux 改用 GBK 只有 M$的东西(或浏览器)才把 等同于 GBK,其实两者是有区别的,字符数量不是一个级别 |
5 imn1 2018-2-22 13:50:18 +08:00 我没写过 C#,不过写过 powershell,也是调用.net ,差不多吧,看着改 $stream=$response.GetResponseStream() $enc=[System.Text.ASCIIEncoding]::GetEncoding(20932) $encu = [System.Text.Encoding]::UTF8 $en_stream=[System.IO.StreamReader]::New($stream,$enc) $data1 = $en_stream.ReadToEnd() $ss = [System.Text.Encoding]::Convert($enc, $encu, $enc.GetBytes($data1)) $data = $encu.getstring($ss) $response 是网页来源 20932 是一个日文编码 |