最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于C#實(shí)現(xiàn)一個(gè)文件編碼轉(zhuǎn)換工具

 更新時(shí)間:2026年04月16日 08:52:06   作者:kaikaile1995  
本文介紹了一個(gè)文件編碼轉(zhuǎn)換工具,支持多種編碼格式轉(zhuǎn)換,如UTF-8、GB2231222312、BIG5等,并具備智能編碼檢測(cè)、批量轉(zhuǎn)換、自動(dòng)添加后綴等功能,主窗體代碼、程序入口及配置文件詳細(xì)說(shuō)明功能特點(diǎn),需要的朋友可以參考下

文件編碼轉(zhuǎn)換工具,支持多種編碼格式之間的轉(zhuǎn)換,包括 UTF-8、UTF-7、Unicode、ASCII、GB2312(簡(jiǎn)體中文)、BIG5(繁體中文)等。

實(shí)現(xiàn)代碼

1. 主窗體代碼 (MainForm.cs)

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace FileEncodingConverter
{
    public partial class MainForm : Form
    {
        private readonly Dictionary<string, Encoding> encodings = new Dictionary<string, Encoding>();
        private readonly List<ConversionResult> conversionResults = new List<ConversionResult>();
        private readonly StringBuilder logBuilder = new StringBuilder();

        public MainForm()
        {
            InitializeComponent();
            InitializeEncodings();
            InitializeUI();
        }

        private void InitializeEncodings()
        {
            // 注冊(cè)編碼提供程序以支持GB2312等特殊編碼
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            
            // 添加支持的編碼
            encodings.Add("UTF-8", Encoding.UTF8);
            encodings.Add("UTF-7", Encoding.UTF7);
            encodings.Add("UTF-16 (LE)", Encoding.Unicode); // Little Endian
            encodings.Add("UTF-16 (BE)", Encoding.BigEndianUnicode); // Big Endian
            encodings.Add("UTF-32", Encoding.UTF32);
            encodings.Add("ASCII", Encoding.ASCII);
            encodings.Add("GB2312 (簡(jiǎn)體中文)", Encoding.GetEncoding("GB2312"));
            encodings.Add("BIG5 (繁體中文)", Encoding.GetEncoding("BIG5"));
            encodings.Add("ISO-8859-1", Encoding.GetEncoding("ISO-8859-1"));
            encodings.Add("Windows-1252", Encoding.GetEncoding(1252));
            encodings.Add("Shift-JIS", Encoding.GetEncoding("shift_jis"));
            encodings.Add("EUC-KR", Encoding.GetEncoding("euc-kr"));
        }

        private void InitializeUI()
        {
            // 窗體設(shè)置
            this.Text = "文件編碼轉(zhuǎn)換工具";
            this.Size = new Size(900, 650);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(240, 243, 249);
            this.Font = new Font("Segoe UI", 9);

            // 創(chuàng)建控件
            int yPos = 20;
            int labelWidth = 120;
            int controlWidth = 300;
            int rowHeight = 35;

            // 源文件選擇
            lblSourceFile = new Label { Text = "源文件:", Location = new Point(20, yPos), Size = new Size(labelWidth, 20), TextAlign = ContentAlignment.MiddleRight };
            txtSourceFile = new TextBox { Location = new Point(150, yPos), Size = new Size(controlWidth, 25), ReadOnly = true };
            btnBrowseSource = new Button { Text = "瀏覽...", Location = new Point(460, yPos), Size = new Size(75, 25), BackColor = Color.SteelBlue, ForeColor = Color.White, FlatStyle = FlatStyle.Flat };
            btnBrowseSource.FlatAppearance.BorderSize = 0;
            btnBrowseSource.Click += BtnBrowseSource_Click;

            // 目標(biāo)文件選擇
            yPos += rowHeight;
            lblTargetFile = new Label { Text = "目標(biāo)文件:", Location = new Point(20, yPos), Size = new Size(labelWidth, 20), TextAlign = ContentAlignment.MiddleRight };
            txtTargetFile = new TextBox { Location = new Point(150, yPos), Size = new Size(controlWidth, 25), ReadOnly = true };
            btnBrowseTarget = new Button { Text = "瀏覽...", Location = new Point(460, yPos), Size = new Size(75, 25), BackColor = Color.SteelBlue, ForeColor = Color.White, FlatStyle = FlatStyle.Flat };
            btnBrowseTarget.FlatAppearance.BorderSize = 0;
            btnBrowseTarget.Click += BtnBrowseTarget_Click;

            // 源編碼選擇
            yPos += rowHeight;
            lblSourceEncoding = new Label { Text = "源編碼:", Location = new Point(20, yPos), Size = new Size(labelWidth, 20), TextAlign = ContentAlignment.MiddleRight };
            cmbSourceEncoding = new ComboBox { Location = new Point(150, yPos), Size = new Size(controlWidth, 25), DropDownStyle = ComboBoxStyle.DropDownList };
            cmbSourceEncoding.Items.AddRange(encodings.Keys.ToArray());
            cmbSourceEncoding.SelectedIndex = 0;

            // 目標(biāo)編碼選擇
            yPos += rowHeight;
            lblTargetEncoding = new Label { Text = "目標(biāo)編碼:", Location = new Point(20, yPos), Size = new Size(labelWidth, 20), TextAlign = ContentAlignment.MiddleRight };
            cmbTargetEncoding = new ComboBox { Location = new Point(150, yPos), Size = new Size(controlWidth, 25), DropDownStyle = ComboBoxStyle.DropDownList };
            cmbTargetEncoding.Items.AddRange(encodings.Keys.ToArray());
            cmbTargetEncoding.SelectedIndex = 0;

            // 轉(zhuǎn)換選項(xiàng)
            yPos += rowHeight;
            chkDetectEncoding = new CheckBox { Text = "自動(dòng)檢測(cè)源文件編碼", Location = new Point(150, yPos), AutoSize = true, Checked = true };
            chkDetectEncoding.CheckedChanged += (s, e) => cmbSourceEncoding.Enabled = !chkDetectEncoding.Checked;

            // 轉(zhuǎn)換按鈕
            yPos += rowHeight + 10;
            btnConvert = new Button { Text = "開(kāi)始轉(zhuǎn)換", Location = new Point(150, yPos), Size = new Size(100, 35), BackColor = Color.ForestGreen, ForeColor = Color.White, FlatStyle = FlatStyle.Flat, Font = new Font("Segoe UI", 10, FontStyle.Bold) };
            btnConvert.FlatAppearance.BorderSize = 0;
            btnConvert.Click += BtnConvert_Click;

            btnBatchConvert = new Button { Text = "批量轉(zhuǎn)換", Location = new Point(260, yPos), Size = new Size(100, 35), BackColor = Color.DodgerBlue, ForeColor = Color.White, FlatStyle = FlatStyle.Flat, Font = new Font("Segoe UI", 10, FontStyle.Bold) };
            btnBatchConvert.FlatAppearance.BorderSize = 0;
            btnBatchConvert.Click += BtnBatchConvert_Click;

            btnStop = new Button { Text = "停止", Location = new Point(370, yPos), Size = new Size(100, 35), BackColor = Color.IndianRed, ForeColor = Color.White, FlatStyle = FlatStyle.Flat, Font = new Font("Segoe UI", 10, FontStyle.Bold), Enabled = false };
            btnStop.FlatAppearance.BorderSize = 0;
            btnStop.Click += BtnStop_Click;

            // 結(jié)果列表
            yPos += rowHeight + 20;
            lstResults = new ListView { Location = new Point(20, yPos), Size = new Size(840, 300), View = View.Details, FullRowSelect = true, GridLines = true };
            lstResults.Columns.Add("源文件", 200);
            lstResults.Columns.Add("目標(biāo)文件", 200);
            lstResults.Columns.Add("源編碼", 80);
            lstResults.Columns.Add("目標(biāo)編碼", 80);
            lstResults.Columns.Add("狀態(tài)", 80);
            lstResults.Columns.Add("大小", 80);
            lstResults.Columns.Add("耗時(shí)", 80);

            // 日志區(qū)域
            yPos += 320;
            lblLog = new Label { Text = "操作日志:", Location = new Point(20, yPos), AutoSize = true };
            yPos += 25;
            txtLog = new TextBox { Location = new Point(20, yPos), Size = new Size(840, 150), Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Vertical, Font = new Font("Consolas", 9) };

            // 狀態(tài)欄
            statusStrip = new StatusStrip();
            toolStripStatusLabel = new ToolStripStatusLabel();
            toolStripProgressBar = new ToolStripProgressBar();
            statusStrip.Items.Add(toolStripStatusLabel);
            statusStrip.Items.Add(toolStripProgressBar);
            statusStrip.Location = new Point(0, this.ClientSize.Height - 22);
            statusStrip.Size = new Size(this.ClientSize.Width, 22);
            statusStrip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;

            // 添加控件到窗體
            this.Controls.AddRange(new Control[] {
                lblSourceFile, txtSourceFile, btnBrowseSource,
                lblTargetFile, txtTargetFile, btnBrowseTarget,
                lblSourceEncoding, cmbSourceEncoding,
                lblTargetEncoding, cmbTargetEncoding,
                chkDetectEncoding,
                btnConvert, btnBatchConvert, btnStop,
                lstResults, lblLog, txtLog, statusStrip
            });

            // 初始化結(jié)果列表
            lstResults.ListViewItemSorter = new ListViewColumnSorter();
        }

        #region 控件聲明
        private Label lblSourceFile, lblTargetFile, lblSourceEncoding, lblTargetEncoding, lblLog;
        private TextBox txtSourceFile, txtTargetFile, txtLog;
        private ComboBox cmbSourceEncoding, cmbTargetEncoding;
        private Button btnBrowseSource, btnBrowseTarget, btnConvert, btnBatchConvert, btnStop;
        private CheckBox chkDetectEncoding;
        private ListView lstResults;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel toolStripStatusLabel;
        private ToolStripProgressBar toolStripProgressBar;
        #endregion

        #region 事件處理
        private void BtnBrowseSource_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "所有文件 (*.*)|*.*";
                openFileDialog.Title = "選擇源文件";
                
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtSourceFile.Text = openFileDialog.FileName;
                    
                    // 自動(dòng)生成目標(biāo)文件名
                    if (string.IsNullOrEmpty(txtTargetFile.Text))
                    {
                        string dir = Path.GetDirectoryName(openFileDialog.FileName);
                        string fileName = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
                        string ext = Path.GetExtension(openFileDialog.FileName);
                        txtTargetFile.Text = Path.Combine(dir, $"{fileName}_converted{ext}");
                    }
                }
            }
        }

        private void BtnBrowseTarget_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "所有文件 (*.*)|*.*";
                saveFileDialog.Title = "選擇目標(biāo)文件";
                
                if (!string.IsNullOrEmpty(txtSourceFile.Text))
                {
                    saveFileDialog.FileName = Path.GetFileName(txtSourceFile.Text);
                }
                
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtTargetFile.Text = saveFileDialog.FileName;
                }
            }
        }

        private async void BtnConvert_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSourceFile.Text) || !File.Exists(txtSourceFile.Text))
            {
                MessageBox.Show("請(qǐng)選擇有效的源文件", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if (string.IsNullOrEmpty(txtTargetFile.Text))
            {
                MessageBox.Show("請(qǐng)指定目標(biāo)文件路徑", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            // 準(zhǔn)備UI
            btnConvert.Enabled = false;
            btnBatchConvert.Enabled = false;
            btnStop.Enabled = true;
            lstResults.Items.Clear();
            conversionResults.Clear();
            logBuilder.Clear();
            txtLog.Clear();
            toolStripProgressBar.Value = 0;
            toolStripStatusLabel.Text = "轉(zhuǎn)換中...";
            
            try
            {
                // 執(zhí)行轉(zhuǎn)換
                var result = await ConvertFileAsync(
                    txtSourceFile.Text, 
                    txtTargetFile.Text, 
                    chkDetectEncoding.Checked ? null : encodings[cmbSourceEncoding.Text],
                    encodings[cmbTargetEncoding.Text]
                );
                
                // 顯示結(jié)果
                AddResultToListView(result);
                LogMessage($"轉(zhuǎn)換完成: {Path.GetFileName(txtSourceFile.Text)}");
            }
            catch (Exception ex)
            {
                LogMessage($"轉(zhuǎn)換失敗: {ex.Message}");
                MessageBox.Show($"轉(zhuǎn)換失敗: {ex.Message}", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢復(fù)UI
                btnConvert.Enabled = true;
                btnBatchConvert.Enabled = true;
                btnStop.Enabled = false;
                toolStripStatusLabel.Text = "就緒";
            }
        }

        private async void BtnBatchConvert_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
            {
                folderDialog.Description = "選擇包含要轉(zhuǎn)換文件的文件夾";
                folderDialog.ShowNewFolderButton = false;
                
                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    string sourceFolder = folderDialog.SelectedPath;
                    string targetFolder = Path.Combine(sourceFolder, "Converted");
                    
                    if (!Directory.Exists(targetFolder))
                    {
                        Directory.CreateDirectory(targetFolder);
                    }
                    
                    // 準(zhǔn)備UI
                    btnConvert.Enabled = false;
                    btnBatchConvert.Enabled = false;
                    btnStop.Enabled = true;
                    lstResults.Items.Clear();
                    conversionResults.Clear();
                    logBuilder.Clear();
                    txtLog.Clear();
                    toolStripProgressBar.Value = 0;
                    toolStripStatusLabel.Text = "批量轉(zhuǎn)換中...";
                    
                    try
                    {
                        // 獲取所有文件
                        var files = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories);
                        int totalFiles = files.Length;
                        int processedFiles = 0;
                        
                        // 處理每個(gè)文件
                        foreach (string file in files)
                        {
                            if (cancellationTokenSource.IsCancellationRequested)
                                break;
                            
                            string relativePath = file.Substring(sourceFolder.Length + 1);
                            string targetFile = Path.Combine(targetFolder, relativePath);
                            string targetDir = Path.GetDirectoryName(targetFile);
                            
                            if (!Directory.Exists(targetDir))
                            {
                                Directory.CreateDirectory(targetDir);
                            }
                            
                            // 執(zhí)行轉(zhuǎn)換
                            var result = await ConvertFileAsync(
                                file, 
                                targetFile, 
                                chkDetectEncoding.Checked ? null : encodings[cmbSourceEncoding.Text],
                                encodings[cmbTargetEncoding.Text]
                            );
                            
                            // 顯示結(jié)果
                            AddResultToListView(result);
                            processedFiles++;
                            
                            // 更新進(jìn)度
                            int progress = (int)((double)processedFiles / totalFiles * 100);
                            toolStripProgressBar.Value = progress;
                            toolStripStatusLabel.Text = $"處理中: {processedFiles}/{totalFiles} 文件";
                        }
                        
                        LogMessage($"批量轉(zhuǎn)換完成! 共處理 {processedFiles} 個(gè)文件");
                    }
                    catch (Exception ex)
                    {
                        LogMessage($"批量轉(zhuǎn)換失敗: {ex.Message}");
                        MessageBox.Show($"批量轉(zhuǎn)換失敗: {ex.Message}", "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // 恢復(fù)UI
                        btnConvert.Enabled = true;
                        btnBatchConvert.Enabled = true;
                        btnStop.Enabled = false;
                        toolStripStatusLabel.Text = "就緒";
                    }
                }
            }
        }

        private void BtnStop_Click(object sender, EventArgs e)
        {
            cancellationTokenSource?.Cancel();
            btnStop.Enabled = false;
            toolStripStatusLabel.Text = "正在停止...";
        }
        #endregion

        #region 核心功能
        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        
        private async Task<ConversionResult> ConvertFileAsync(
            string sourceFile, 
            string targetFile, 
            Encoding sourceEncoding, 
            Encoding targetEncoding)
        {
            var result = new ConversionResult
            {
                SourceFile = sourceFile,
                TargetFile = targetFile,
                SourceEncoding = sourceEncoding?.EncodingName ?? "自動(dòng)檢測(cè)",
                TargetEncoding = targetEncoding.EncodingName,
                StartTime = DateTime.Now
            };
            
            try
            {
                // 檢測(cè)源文件編碼(如果需要)
                if (sourceEncoding == null)
                {
                    sourceEncoding = DetectFileEncoding(sourceFile);
                    result.SourceEncoding = sourceEncoding.EncodingName;
                }
                
                // 讀取源文件內(nèi)容
                string content = await Task.Run(() => File.ReadAllText(sourceFile, sourceEncoding));
                
                // 寫入目標(biāo)文件
                await Task.Run(() => File.WriteAllText(targetFile, content, targetEncoding));
                
                // 獲取文件大小
                FileInfo fileInfo = new FileInfo(targetFile);
                result.Size = fileInfo.Length;
                result.Status = "成功";
            }
            catch (Exception ex)
            {
                result.Status = $"失敗: {ex.Message}";
            }
            finally
            {
                result.EndTime = DateTime.Now;
                result.Duration = result.EndTime - result.StartTime;
            }
            
            return result;
        }
        
        private Encoding DetectFileEncoding(string filePath)
        {
            // 使用BOM檢測(cè)編碼
            var bom = new byte[4];
            using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                file.Read(bom, 0, 4);
            }
            
            // 檢查BOM
            if (bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF)
                return Encoding.UTF8;
            if (bom[0] == 0xFE && bom[1] == 0xFF)
                return Encoding.BigEndianUnicode;
            if (bom[0] == 0xFF && bom[1] == 0xFE)
            {
                if (bom[2] == 0x00 && bom[3] == 0x00)
                    return Encoding.UTF32;
                return Encoding.Unicode;
            }
            if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == 0xFE && bom[3] == 0xFF)
                return Encoding.UTF32;
            if (bom[0] == 0x2B && bom[1] == 0x2F && bom[2] == 0x76)
                return Encoding.UTF7;
            
            // 沒(méi)有BOM,使用啟發(fā)式檢測(cè)
            return DetectEncodingWithoutBom(filePath);
        }
        
        private Encoding DetectEncodingWithoutBom(string filePath)
        {
            // 使用簡(jiǎn)單啟發(fā)式方法檢測(cè)編碼
            int utf8Count = 0;
            int asciiCount = 0;
            int chineseCount = 0;
            
            using (var reader = new StreamReader(filePath, Encoding.Default, true))
            {
                string content = reader.ReadToEnd();
                
                // 檢查是否包含中文字符
                foreach (char c in content)
                {
                    if (c > 127)
                    {
                        chineseCount++;
                    }
                }
                
                // 檢查UTF-8特征
                try
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(content);
                    string decoded = Encoding.UTF8.GetString(bytes);
                    if (decoded == content) utf8Count++;
                }
                catch { }
                
                // 檢查ASCII特征
                try
                {
                    byte[] bytes = Encoding.ASCII.GetBytes(content);
                    string decoded = Encoding.ASCII.GetString(bytes);
                    if (decoded == content) asciiCount++;
                }
                catch { }
            }
            
            // 根據(jù)特征選擇編碼
            if (chineseCount > 0)
            {
                // 如果包含中文字符,嘗試GB2312或BIG5
                if (filePath.Contains("簡(jiǎn)體") || filePath.Contains("GB"))
                    return Encoding.GetEncoding("GB2312");
                return Encoding.GetEncoding("BIG5");
            }
            else if (utf8Count > 0)
            {
                return Encoding.UTF8;
            }
            else
            {
                return Encoding.Default; // 使用系統(tǒng)默認(rèn)編碼
            }
        }
        
        private void AddResultToListView(ConversionResult result)
        {
            var item = new ListViewItem(Path.GetFileName(result.SourceFile));
            item.SubItems.Add(Path.GetFileName(result.TargetFile));
            item.SubItems.Add(result.SourceEncoding);
            item.SubItems.Add(result.TargetEncoding);
            item.SubItems.Add(result.Status);
            item.SubItems.Add(FormatFileSize(result.Size));
            item.SubItems.Add($"{result.Duration.TotalMilliseconds:0} ms");
            item.Tag = result;
            
            // 根據(jù)狀態(tài)設(shè)置顏色
            if (result.Status.StartsWith("成功"))
                item.ForeColor = Color.Green;
            else
                item.ForeColor = Color.Red;
            
            lstResults.Items.Add(item);
            conversionResults.Add(result);
        }
        
        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            int order = 0;
            double len = bytes;
            
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len /= 1024;
            }
            
            return $"{len:0.##} {sizes[order]}";
        }
        
        private void LogMessage(string message)
        {
            string logEntry = $"[{DateTime.Now:HH:mm:ss}] {message}";
            logBuilder.AppendLine(logEntry);
            txtLog.AppendText(logEntry + Environment.NewLine);
            txtLog.ScrollToCaret();
        }
        #endregion

        #region 輔助類
        private class ConversionResult
        {
            public string SourceFile { get; set; }
            public string TargetFile { get; set; }
            public string SourceEncoding { get; set; }
            public string TargetEncoding { get; set; }
            public string Status { get; set; }
            public long Size { get; set; }
            public DateTime StartTime { get; set; }
            public DateTime EndTime { get; set; }
            public TimeSpan Duration { get; set; }
        }
        
        private class ListViewColumnSorter : System.Collections.IComparer
        {
            private int columnIndex;
            private SortOrder sortOrder;
            
            public ListViewColumnSorter()
            {
                columnIndex = 0;
                sortOrder = SortOrder.Ascending;
            }
            
            public int Compare(object x, object y)
            {
                ListViewItem item1 = (ListViewItem)x;
                ListViewItem item2 = (ListViewItem)y;
                
                string text1 = item1.SubItems[columnIndex].Text;
                string text2 = item2.SubItems[columnIndex].Text;
                
                if (double.TryParse(text1, out double num1) && 
                    double.TryParse(text2, out double num2))
                {
                    return sortOrder == SortOrder.Ascending ? 
                        num1.CompareTo(num2) : num2.CompareTo(num1);
                }
                
                return sortOrder == SortOrder.Ascending ? 
                    string.Compare(text1, text2) : string.Compare(text2, text1);
            }
        }
        #endregion
    }
}

2. 程序入口 (Program.cs)

using System;
using System.Windows.Forms;

namespace FileEncodingConverter
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

3. 應(yīng)用程序配置文件 (App.config)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

功能特點(diǎn)

1. 多編碼支持

  • 國(guó)際編碼:UTF-8、UTF-7、UTF-16 (LE/BE)、UTF-32、ASCII
  • 中文編碼:GB2312 (簡(jiǎn)體中文)、BIG5 (繁體中文)
  • 其他編碼:ISO-8859-1、Windows-1252、Shift-JIS、EUC-KR
  • 自動(dòng)檢測(cè):智能檢測(cè)源文件編碼

2. 轉(zhuǎn)換模式

  • 單文件轉(zhuǎn)換:選擇單個(gè)源文件進(jìn)行轉(zhuǎn)換
  • 批量轉(zhuǎn)換:整個(gè)文件夾批量轉(zhuǎn)換
  • 自動(dòng)生成目標(biāo)文件:自動(dòng)添加"_converted"后綴

3. 用戶友好界面

  • 直觀操作:清晰的文件選擇和編碼選擇
  • 實(shí)時(shí)日志:顯示詳細(xì)的操作日志
  • 結(jié)果列表:表格形式展示轉(zhuǎn)換結(jié)果
  • 狀態(tài)指示:顏色標(biāo)識(shí)成功/失敗狀態(tài)
  • 進(jìn)度顯示:進(jìn)度條顯示處理進(jìn)度

4. 高級(jí)功能

  • 編碼檢測(cè):智能檢測(cè)無(wú)BOM文件的編碼
  • 大文件處理:流式處理避免內(nèi)存溢出
  • 錯(cuò)誤處理:詳細(xì)的錯(cuò)誤信息和異常捕獲
  • 性能優(yōu)化:異步處理避免界面卡頓

技術(shù)實(shí)現(xiàn)細(xì)節(jié)

1. 編碼檢測(cè)算法

private Encoding DetectFileEncoding(string filePath)
{
    // 使用BOM檢測(cè)編碼
    var bom = new byte[4];
    using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        file.Read(bom, 0, 4);
    }
    
    // 檢查BOM
    if (bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF)
        return Encoding.UTF8;
    if (bom[0] == 0xFE && bom[1] == 0xFF)
        return Encoding.BigEndianUnicode;
    if (bom[0] == 0xFF && bom[1] == 0xFE)
    {
        if (bom[2] == 0x00 && bom[3] == 0x00)
            return Encoding.UTF32;
        return Encoding.Unicode;
    }
    if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == 0xFE && bom[3] == 0xFF)
        return Encoding.UTF32;
    if (bom[0] == 0x2B && bom[1] == 0x2F && bom[2] == 0x76)
        return Encoding.UTF7;
    
    // 沒(méi)有BOM,使用啟發(fā)式檢測(cè)
    return DetectEncodingWithoutBom(filePath);
}

2. 文件轉(zhuǎn)換核心

private async Task<ConversionResult> ConvertFileAsync(
    string sourceFile, 
    string targetFile, 
    Encoding sourceEncoding, 
    Encoding targetEncoding)
{
    var result = new ConversionResult
    {
        SourceFile = sourceFile,
        TargetFile = targetFile,
        SourceEncoding = sourceEncoding?.EncodingName ?? "自動(dòng)檢測(cè)",
        TargetEncoding = targetEncoding.EncodingName,
        StartTime = DateTime.Now
    };
    
    try
    {
        // 檢測(cè)源文件編碼(如果需要)
        if (sourceEncoding == null)
        {
            sourceEncoding = DetectFileEncoding(sourceFile);
            result.SourceEncoding = sourceEncoding.EncodingName;
        }
        
        // 讀取源文件內(nèi)容
        string content = await Task.Run(() => File.ReadAllText(sourceFile, sourceEncoding));
        
        // 寫入目標(biāo)文件
        await Task.Run(() => File.WriteAllText(targetFile, content, targetEncoding));
        
        // 獲取文件大小
        FileInfo fileInfo = new FileInfo(targetFile);
        result.Size = fileInfo.Length;
        result.Status = "成功";
    }
    catch (Exception ex)
    {
        result.Status = $"失敗: {ex.Message}";
    }
    finally
    {
        result.EndTime = DateTime.Now;
        result.Duration = result.EndTime - result.StartTime;
    }
    
    return result;
}

3. 批量處理實(shí)現(xiàn)

private async void BtnBatchConvert_Click(object sender, EventArgs e)
{
    // 選擇源文件夾
    using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
    {
        if (folderDialog.ShowDialog() == DialogResult.OK)
        {
            string sourceFolder = folderDialog.SelectedPath;
            string targetFolder = Path.Combine(sourceFolder, "Converted");
            
            // 創(chuàng)建目標(biāo)文件夾
            Directory.CreateDirectory(targetFolder);
            
            // 獲取所有文件
            var files = Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories);
            int totalFiles = files.Length;
            int processedFiles = 0;
            
            // 處理每個(gè)文件
            foreach (string file in files)
            {
                if (cancellationTokenSource.IsCancellationRequested)
                    break;
                
                // 構(gòu)建目標(biāo)路徑
                string relativePath = file.Substring(sourceFolder.Length + 1);
                string targetFile = Path.Combine(targetFolder, relativePath);
                string targetDir = Path.GetDirectoryName(targetFile);
                
                // 創(chuàng)建子目錄
                Directory.CreateDirectory(targetDir);
                
                // 執(zhí)行轉(zhuǎn)換
                var result = await ConvertFileAsync(
                    file, 
                    targetFile, 
                    chkDetectEncoding.Checked ? null : encodings[cmbSourceEncoding.Text],
                    encodings[cmbTargetEncoding.Text]
                );
                
                // 顯示結(jié)果
                AddResultToListView(result);
                processedFiles++;
                
                // 更新進(jìn)度
                int progress = (int)((double)processedFiles / totalFiles * 100);
                toolStripProgressBar.Value = progress;
            }
        }
    }
}

使用說(shuō)明

1. 單文件轉(zhuǎn)換

  1. 點(diǎn)擊"瀏覽…"選擇源文件
  2. 選擇目標(biāo)文件路徑(自動(dòng)生成或手動(dòng)指定)
  3. 選擇源編碼(或勾選"自動(dòng)檢測(cè)")
  4. 選擇目標(biāo)編碼
  5. 點(diǎn)擊"開(kāi)始轉(zhuǎn)換"

2. 批量轉(zhuǎn)換

  1. 點(diǎn)擊"批量轉(zhuǎn)換"按鈕
  2. 選擇包含要轉(zhuǎn)換文件的文件夾
  3. 程序自動(dòng)創(chuàng)建"Converted"子文件夾存放結(jié)果
  4. 選擇源編碼(或勾選"自動(dòng)檢測(cè)")
  5. 選擇目標(biāo)編碼
  6. 程序自動(dòng)處理所有文件

3. 結(jié)果查看

  • 結(jié)果列表:顯示所有轉(zhuǎn)換操作的詳細(xì)信息
  • 狀態(tài)列:綠色表示成功,紅色表示失敗
  • 日志區(qū)域:顯示詳細(xì)的操作日志
  • 狀態(tài)欄:顯示當(dāng)前處理進(jìn)度

參考代碼 C# 文件編碼轉(zhuǎn)換工具(支持UTF-8/UTF-7/Unicode/ASCII/GB2312(簡(jiǎn)體中文)/BIG5 (繁體中文)等編碼轉(zhuǎn)換 ) www.youwenfan.com/contentcst/49413.html

擴(kuò)展功能建議

1. 添加文件預(yù)覽功能

private void PreviewFile(string filePath, Encoding encoding)
{
    try
    {
        string content = File.ReadAllText(filePath, encoding);
        var previewForm = new Form
        {
            Text = $"預(yù)覽: {Path.GetFileName(filePath)}",
            Size = new Size(800, 600)
        };
        
        var textBox = new TextBox
        {
            Multiline = true,
            ScrollBars = ScrollBars.Both,
            Dock = DockStyle.Fill,
            Text = content,
            Font = new Font("Consolas", 10)
        };
        
        previewForm.Controls.Add(textBox);
        previewForm.ShowDialog();
    }
    catch (Exception ex)
    {
        MessageBox.Show($"預(yù)覽失敗: {ex.Message}", "錯(cuò)誤", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

2. 添加編碼修復(fù)功能

private void FixEncoding(string filePath, Encoding correctEncoding)
{
    try
    {
        // 以錯(cuò)誤編碼讀取
        string content = File.ReadAllText(filePath, Encoding.Default);
        
        // 以正確編碼重新寫入
        File.WriteAllText(filePath, content, correctEncoding);
        
        LogMessage($"已修復(fù)文件編碼: {Path.GetFileName(filePath)}");
    }
    catch (Exception ex)
    {
        LogMessage($"修復(fù)失敗: {ex.Message}");
    }
}

3. 添加文件比較功能

private void CompareFiles(string file1, string file2)
{
    try
    {
        string content1 = File.ReadAllText(file1);
        string content2 = File.ReadAllText(file2);
        
        if (content1 == content2)
        {
            MessageBox.Show("文件內(nèi)容完全相同", "比較結(jié)果", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            // 使用差異比較工具
            // 這里可以集成第三方比較工具
            MessageBox.Show("文件內(nèi)容不同", "比較結(jié)果", 
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"比較失敗: {ex.Message}", "錯(cuò)誤", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

4. 添加編碼統(tǒng)計(jì)功能

private void AnalyzeFolderEncoding(string folderPath)
{
    try
    {
        var encodingStats = new Dictionary<string, int>();
        var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
        
        foreach (string file in files)
        {
            try
            {
                Encoding encoding = DetectFileEncoding(file);
                string encodingName = encoding.EncodingName;
                
                if (!encodingStats.ContainsKey(encodingName))
                {
                    encodingStats[encodingName] = 0;
                }
                
                encodingStats[encodingName]++;
            }
            catch
            {
                // 忽略無(wú)法檢測(cè)的文件
            }
        }
        
        // 顯示統(tǒng)計(jì)結(jié)果
        ShowEncodingStatistics(encodingStats);
    }
    catch (Exception ex)
    {
        MessageBox.Show($"分析失敗: {ex.Message}", "錯(cuò)誤", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

常見(jiàn)問(wèn)題解決

1. 編碼檢測(cè)錯(cuò)誤

  • 問(wèn)題:自動(dòng)檢測(cè)編碼不準(zhǔn)確
  • 解決
    • 對(duì)于已知編碼的文件,取消"自動(dòng)檢測(cè)"并手動(dòng)選擇
    • 使用專業(yè)文本編輯器(如Notepad++)確認(rèn)實(shí)際編碼
    • 在程序中添加更多啟發(fā)式規(guī)則

2. 轉(zhuǎn)換后亂碼

  • 問(wèn)題:轉(zhuǎn)換后出現(xiàn)亂碼
  • 解決
    • 確認(rèn)源文件的實(shí)際編碼
    • 嘗試不同的源編碼設(shè)置
    • 使用"自動(dòng)檢測(cè)"功能
    • 對(duì)于特殊字符,使用UTF-8編碼

3. 大文件處理

  • 問(wèn)題:處理大文件時(shí)內(nèi)存不足
  • 解決
    • 使用流式處理(StreamReader/StreamWriter)
    • 分塊讀取和寫入文件
    • 增加系統(tǒng)虛擬內(nèi)存
    • 使用64位應(yīng)用程序

4. 特殊字符處理

  • 問(wèn)題:某些特殊字符無(wú)法正確轉(zhuǎn)換
  • 解決
    • 使用UTF-8編碼處理多語(yǔ)言文本
    • 對(duì)于特殊符號(hào),使用Unicode轉(zhuǎn)義序列
    • 在轉(zhuǎn)換前進(jìn)行字符替換

項(xiàng)目總結(jié)

這個(gè)文件編碼轉(zhuǎn)換工具提供了完整的解決方案,具有以下特點(diǎn):

全面的編碼支持

  • 支持12+種常見(jiàn)編碼格式
  • 智能檢測(cè)無(wú)BOM文件的編碼
  • 正確處理中文字符集

高效的轉(zhuǎn)換引擎

  • 異步處理避免界面卡頓
  • 批量轉(zhuǎn)換支持
  • 流式處理大文件

用戶友好的界面

  • 直觀的操作流程
  • 詳細(xì)的結(jié)果展示
  • 實(shí)時(shí)的操作日志
  • 進(jìn)度和狀態(tài)反饋

健壯的錯(cuò)誤處理

  • 全面的異常捕獲
  • 詳細(xì)的錯(cuò)誤信息
  • 可恢復(fù)的操作流程

擴(kuò)展性設(shè)計(jì)

  • 模塊化架構(gòu)
  • 易于添加新功能
  • 支持插件式擴(kuò)展

以上就是基于C#實(shí)現(xiàn)一個(gè)文件編碼轉(zhuǎn)換工具的詳細(xì)內(nèi)容,更多關(guān)于C#文件編碼轉(zhuǎn)換工具的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#圖像灰度級(jí)拉伸的方法

    C#圖像灰度級(jí)拉伸的方法

    這篇文章主要介紹了C#圖像灰度級(jí)拉伸的方法,涉及C#灰度操作的相關(guān)技巧,需要的朋友可以參考下
    2015-04-04
  • C#做線形圖的方法

    C#做線形圖的方法

    在本篇內(nèi)容中小編給大家總結(jié)了C#怎么做線形圖的教程內(nèi)容,對(duì)此有需要的朋友們可以跟著學(xué)習(xí)下。
    2018-12-12
  • C# ConfigHelper 輔助類介紹

    C# ConfigHelper 輔助類介紹

    ConfigHelper(包含AppConfig和WebConfig), app.config和web.config的[appSettings]和[connectionStrings]節(jié)點(diǎn)進(jìn)行新增、修改、刪除和讀取相關(guān)的操作。
    2013-04-04
  • 利用C#實(shí)現(xiàn)分割GIF圖片

    利用C#實(shí)現(xiàn)分割GIF圖片

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)分割GIF圖片的功能,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以了解一下
    2022-12-12
  • C#如何操作Excel數(shù)據(jù)透視表

    C#如何操作Excel數(shù)據(jù)透視表

    這篇文章主要為大家詳細(xì)介紹了C#如何操作Excel數(shù)據(jù)透視表, 創(chuàng)建透視表、設(shè)置行折疊、展開(kāi)等操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • C#如何批量修改圖片尺寸和DPI

    C#如何批量修改圖片尺寸和DPI

    這篇文章主要介紹了C#批量修改圖片尺寸和DPI方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-05-05
  • C#用表達(dá)式樹(shù)構(gòu)建動(dòng)態(tài)查詢的方法

    C#用表達(dá)式樹(shù)構(gòu)建動(dòng)態(tài)查詢的方法

    這篇文章主要介紹了C#用表達(dá)式樹(shù)構(gòu)建動(dòng)態(tài)查詢的方法,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下
    2020-12-12
  • C#圖表開(kāi)發(fā)之Chart詳解

    C#圖表開(kāi)發(fā)之Chart詳解

    C#中的Chart控件用于開(kāi)發(fā)圖表功能,具有Series和ChartArea兩個(gè)重要屬性,Series屬性是SeriesCollection類型,包含多個(gè)Series對(duì)象,每個(gè)Series代表圖表中的一個(gè)數(shù)據(jù)系列,Series對(duì)象有一個(gè)Points屬性,用于存儲(chǔ)數(shù)據(jù)點(diǎn),每個(gè)數(shù)據(jù)點(diǎn)是一個(gè)DataPoint對(duì)象
    2024-12-12
  • C#利用Label標(biāo)簽控件模擬窗體標(biāo)題的移動(dòng)及窗體顏色不斷變換效果

    C#利用Label標(biāo)簽控件模擬窗體標(biāo)題的移動(dòng)及窗體顏色不斷變換效果

    Label標(biāo)簽控件相信對(duì)大家來(lái)說(shuō)都不陌生,下面這篇文章主要給大家介紹了關(guān)于C#利用Label標(biāo)簽控件模擬窗體標(biāo)題的移動(dòng)及窗體顏色不斷變換效果的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。
    2017-12-12
  • C#值類型、引用類型、泛型、集合、調(diào)用函數(shù)的表達(dá)式樹(shù)實(shí)踐

    C#值類型、引用類型、泛型、集合、調(diào)用函數(shù)的表達(dá)式樹(shù)實(shí)踐

    本文詳細(xì)講解了C#值類型、引用類型、泛型、集合、調(diào)用函數(shù)的表達(dá)式樹(shù)實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-01-01

最新評(píng)論

隆化县| 平阳县| 凤凰县| 历史| 武山县| 黔东| 兰西县| 左权县| 灌阳县| 襄汾县| 榆树市| 崇阳县| 布尔津县| 苗栗市| 开封市| 南投市| 长春市| 乌鲁木齐县| 桂林市| 楚雄市| 嵊州市| 曲水县| 仙游县| 昭苏县| 石棉县| 靖西县| 扬州市| 甘孜县| 三明市| 馆陶县| 德清县| 和政县| 信丰县| 南召县| 华阴市| 和龙市| 涿州市| 延长县| 桂阳县| 盐边县| 滁州市|