Wednesday, March 16, 2011

C# Code to change the encoding of a text file to the desired encoding

This code lets you convert multiple files in a directory to the desired encoding. The reason for this utility is the source control which is being used by my client doesn't support anything other than ASCII (7 bit). By default, some of the program creates files with UTF-8 encoding, which created the problem. I wrote this small program which will convert the files in a stretch and hence might save lot of time. Enjoy!




Code Behind :


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 BulkEncodingChanger
{
    ///
    ///
    ///
   
    public partial class frmBulkEncoder : Form
    {
        public frmBulkEncoder()
        {
            InitializeComponent();
        }

        private void btnFolderBrowse_Click(object sender, EventArgs e)
        {
            //Do - Show the folder browser dialog
            try
            {
                dlgFolderBrowserDialog.ShowDialog();
                if (!dlgFolderBrowserDialog.SelectedPath.Trim().Equals(""))
                {
                    txtSourceFolder.Text = dlgFolderBrowserDialog.SelectedPath.Trim();
                }

            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.Print(exp.Message.ToString());
                System.Diagnostics.Debug.Print(exp.ToString());
            }

        }

        private void frmBulkEncoder_Load(object sender, EventArgs e)
        {
            //ListBox test;
            //System.Text.Encoding.UTF8;
            lstEncodings.Items.Add("System Default");
            lstEncodings.Items.Add("ASCII");
            lstEncodings.Items.Add("Unicode");
            lstEncodings.Items.Add("UTF-7");
            lstEncodings.Items.Add("UTF-8");
            lstEncodings.Items.Add("UTF-32");
            lstEncodings.Items.Add("Big Endian Unicode");

            lstEncodings.SelectedItem = lstEncodings.Items[0];
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Encoding encEncodingFormat = Encoding.Default;
            string strUserTemp="";
            char[] charBuffer;
            int bytReadBytes;
            try
            {
                charBuffer = new char[2050];

               
                if (txtSourceFolder.Text.Trim().Equals(""))
                {
                    MessageBox.Show(this, "Please select a folder to process!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else if (!Directory.Exists(txtSourceFolder.Text.Trim()))
                {
                    MessageBox.Show(this, "Selected Folder does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    //Do the processing here.

                    FileInfo[] fi;
                    DirectoryInfo di;
                    string strFileTemp1,strFileTemp2;
                    //Directory.get
                    //lstEncodings.Items.Add("System Default");
                    //lstEncodings.Items.Add("ASCII");
                    //lstEncodings.Items.Add("Unicode");
                    //lstEncodings.Items.Add("UTF-7");
                    //lstEncodings.Items.Add("UTF-8");
                    //lstEncodings.Items.Add("UTF-32");

                    if (lstEncodings.SelectedItem.ToString().Equals("System Default"))
                    {
                        encEncodingFormat = Encoding.Default;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("ASCII"))
                    {
                        encEncodingFormat = Encoding.ASCII;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("Unicode"))
                    {
                        encEncodingFormat = Encoding.Unicode;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("UTF-7"))
                    {
                        encEncodingFormat = Encoding.UTF7;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("UTF-8"))
                    {
                        encEncodingFormat = Encoding.UTF8;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("UTF-32"))
                    {
                        encEncodingFormat = Encoding.UTF32;
                    }
                    else if (lstEncodings.SelectedItem.ToString().Equals("Big Endian Unicode"))
                    {
                        encEncodingFormat = Encoding.BigEndianUnicode;
                    }
                    else
                    {
                        encEncodingFormat = Encoding.Default;
                    }


                    di=new DirectoryInfo(txtSourceFolder.Text.Trim());
                    strUserTemp = Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
                    if (!strUserTemp.EndsWith("\\"))
                    {
                        strUserTemp += "\\";
                    }
                    strUserTemp += "TempEnc";

                    if (!Directory.Exists(strUserTemp))
                    {
                        Directory.CreateDirectory(strUserTemp);
                    }
                    strUserTemp += "\\";

                    fi=di.GetFiles(txtFilter.Text.Trim());

                    foreach (FileInfo oFI in fi)
                    {
                        //Get the user's App data path.
                        strFileTemp1 = oFI.FullName;
                        strFileTemp2 = oFI.Name;
                        StreamReader oReader = new StreamReader(strFileTemp1);
                        if (File.Exists(strUserTemp + strFileTemp2))
                        {
                            File.Delete(strUserTemp + strFileTemp2);
                        }
                        StreamWriter oWriter = new StreamWriter(strUserTemp + strFileTemp2, false, encEncodingFormat);

                        while (!oReader.EndOfStream)
                        {
                            bytReadBytes = oReader.Read(charBuffer, 0, 2048);

                            oWriter.Write(charBuffer, 0, bytReadBytes);
                        }

                        oReader.Close();
                        oWriter.Close();

                        if(File.Exists(strUserTemp + strFileTemp2 + ".tmp1"))
                        {
                            File.Delete(strUserTemp + strFileTemp2 + ".tmp1");
                        }
                        File.Move(strFileTemp1, strUserTemp + strFileTemp2 + ".tmp1");
                        File.Move(strUserTemp + strFileTemp2, strFileTemp1);
                    }

                    MessageBox.Show("Operation Complete!");
                }
               
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.Print(exp.Message.ToString());
                System.Diagnostics.Debug.Print(exp.ToString());
                MessageBox.Show(this, exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

          
        }
    }
}

Form Designer code :


namespace BulkEncodingChanger
{
    partial class frmBulkEncoder
    {
        ///
        /// Required designer variable.
        ///
        private System.ComponentModel.IContainer components = null;

        ///
        /// Clean up any resources being used.
        ///
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        ///
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmBulkEncoder));
            this.btnStart = new System.Windows.Forms.Button();
            this.dlgFolderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
            this.txtSourceFolder = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.btnFolderBrowse = new System.Windows.Forms.Button();
            this.lstEncodings = new System.Windows.Forms.ListBox();
            this.label2 = new System.Windows.Forms.Label();
            this.txtFilter = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.btnSelectSpecificFiles = new System.Windows.Forms.Button();
            this.txtSelectedFiles = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // btnStart
            //
            this.btnStart.Location = new System.Drawing.Point(185, 298);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 0;
            this.btnStart.Text = "&Start!";
            this.btnStart.UseVisualStyleBackColor = true;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            //
            // txtSourceFolder
            //
            this.txtSourceFolder.Location = new System.Drawing.Point(150, 52);
            this.txtSourceFolder.Name = "txtSourceFolder";
            this.txtSourceFolder.Size = new System.Drawing.Size(236, 20);
            this.txtSourceFolder.TabIndex = 1;
            this.txtSourceFolder.Text = "C:\\Temp";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(76, 55);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(36, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "Folder";
            //
            // btnFolderBrowse
            //
            this.btnFolderBrowse.Location = new System.Drawing.Point(392, 49);
            this.btnFolderBrowse.Name = "btnFolderBrowse";
            this.btnFolderBrowse.Size = new System.Drawing.Size(24, 23);
            this.btnFolderBrowse.TabIndex = 3;
            this.btnFolderBrowse.Text = "....";
            this.btnFolderBrowse.UseVisualStyleBackColor = true;
            this.btnFolderBrowse.Click += new System.EventHandler(this.btnFolderBrowse_Click);
            //
            // lstEncodings
            //
            this.lstEncodings.FormattingEnabled = true;
            this.lstEncodings.Location = new System.Drawing.Point(150, 168);
            this.lstEncodings.Name = "lstEncodings";
            this.lstEncodings.Size = new System.Drawing.Size(184, 95);
            this.lstEncodings.TabIndex = 4;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(46, 168);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(86, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Target Encoding";
            //
            // txtFilter
            //
            this.txtFilter.Location = new System.Drawing.Point(150, 90);
            this.txtFilter.Name = "txtFilter";
            this.txtFilter.Size = new System.Drawing.Size(93, 20);
            this.txtFilter.TabIndex = 6;
            this.txtFilter.Text = "*.sql";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(76, 93);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(29, 13);
            this.label3.TabIndex = 2;
            this.label3.Text = "Filter";
            //
            // btnSelectSpecificFiles
            //
            this.btnSelectSpecificFiles.Enabled = false;
            this.btnSelectSpecificFiles.Location = new System.Drawing.Point(269, 90);
            this.btnSelectSpecificFiles.Name = "btnSelectSpecificFiles";
            this.btnSelectSpecificFiles.Size = new System.Drawing.Size(133, 23);
            this.btnSelectSpecificFiles.TabIndex = 7;
            this.btnSelectSpecificFiles.Text = "Select Specific Files";
            this.btnSelectSpecificFiles.UseVisualStyleBackColor = true;
            //
            // txtSelectedFiles
            //
            this.txtSelectedFiles.Location = new System.Drawing.Point(365, 146);
            this.txtSelectedFiles.Multiline = true;
            this.txtSelectedFiles.Name = "txtSelectedFiles";
            this.txtSelectedFiles.ReadOnly = true;
            this.txtSelectedFiles.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtSelectedFiles.Size = new System.Drawing.Size(299, 223);
            this.txtSelectedFiles.TabIndex = 8;
            this.txtSelectedFiles.Visible = false;
            //
            // frmBulkEncoder
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(693, 401);
            this.Controls.Add(this.txtSelectedFiles);
            this.Controls.Add(this.btnSelectSpecificFiles);
            this.Controls.Add(this.txtFilter);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.lstEncodings);
            this.Controls.Add(this.btnFolderBrowse);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtSourceFolder);
            this.Controls.Add(this.btnStart);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "frmBulkEncoder";
            this.Text = "Bulk Encoding Changer";
            this.Load += new System.EventHandler(this.frmBulkEncoder_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.FolderBrowserDialog dlgFolderBrowserDialog;
        private System.Windows.Forms.TextBox txtSourceFolder;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnFolderBrowse;
        private System.Windows.Forms.ListBox lstEncodings;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtFilter;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button btnSelectSpecificFiles;
        private System.Windows.Forms.TextBox txtSelectedFiles;
    }
}