Консольный кодировщик файлов в UTF-8

Лучший способ помочь другим, поделиться своими находками.

Консольный кодировщик файлов в UTF-8

Сообщение Andy Ion 11 мар 2012, 14:59

Маленькая консольная утилита, кодирующая .cs файлы в UTF-8 рекурсивно от текущей директории. Очень полезна, когда в проекте уже много файлов в другой кодировке и их нужно перекодировать.
Чтобы выбрать другую кодировку - смените на нужную в строке File.WriteAllText(f.FullName, s, Encoding.UTF8);
Большое количество комментариев поможет в понимании её работы, хоть она и весьма примитивная.

Синтаксис:
Используется csharp
using System;
using System.IO;
using System.Text;

namespace EncodingFixer
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Program exe = new Program(); //new link for a Program class
            //definitions for a border drawing strings
            const string startBorder = "================================================================\n";
            string progStartedText = "Program started in [" + DateTime.Now + "]";

            try //let's try to display start border
            {
                int formatter = (startBorder.Length - 2) - progStartedText.Length; //calculate difference between startBorder and progStartedText, -2 means to not include "\n" in length
                for (int i = 0; i < formatter / 2; i++) //we will repeat cycle half of times from formatter length
                {
                    progStartedText = i == 0 ? " " + progStartedText + " " : "#" + progStartedText + "#"; //if this is the first cycle (i==0), we will add spaces from each side of string, else we will add sharp symbol
                }
                progStartedText = "######" + progStartedText + "####\n"; //final trimming to get row length visual identical to startBorder
                //And here we can draw our border with progStartedText!
                File.AppendAllText("EncodingFixer.log", startBorder);
                File.AppendAllText("EncodingFixer.log", progStartedText);
                File.AppendAllText("EncodingFixer.log", startBorder);
            }
            catch (IOException ioException) //if something wrong with reading/writing
            {
                Console.WriteLine("[" + DateTime.Now + "] " + ioException); //write about exception to log
            }

            try
            {
                switch (args[0]) //read parameter from start shortcut
                {
                    case "/q": //if we started with /q parameter
                        File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + "Launching fixer in silent mode\n"); //log about that
                        exe.Go(true); //activate silent mode in Go class
                        break;
                }
            }
            catch (IndexOutOfRangeException) //if args is blank but NOT NULL e.g. program launched without parameters
            {
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + "Launching fixer without parameters\n"); //log about that
                exe.Go(false); //disable silent mode in Go class
            }
        }

        protected void Go(bool silentMode) //main processing class
        {
            try //let's try thingz
            {
                FileInfo[] fi = new DirectoryInfo(@"...").GetFiles("*.cs", SearchOption.AllDirectories); //make an array with all .cs files in this folder and subfolders
                foreach (FileInfo f in fi) //for every file in our array
                {
                    string s = File.ReadAllText(f.FullName); //read it text
                    if (!silentMode) //if silent mode disabled
                    {
                        Console.WriteLine("[" + DateTime.Now + "] " + "Processing " + f.FullName); //write about processing into console window
                    }
                    File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + "Processing " + f.FullName + "\n"); //write about processing into log file
                    File.WriteAllText(f.FullName, s, Encoding.UTF8); //write file back with UTF-8 encoding
                }
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + "All files encoded successfully!\n"); //write about successful operation into log file
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + "Encoding fixer by Andy Ion\n" + "[" + DateTime.Now + "] " + "Holy Cow Studio, 2010-2012 http://www.holycowstudio.ru\n"); //write some advert into log file

                if (!silentMode) //if silent mode disabled, show upper messages in console window
                {
                    Console.WriteLine("[" + DateTime.Now + "] " + "All files encoded successfully!");
                    Console.WriteLine("[" + DateTime.Now + "] " + "Encoding fixer by Andy Ion\n" + "[" + DateTime.Now + "] " + "Holy Cow Studio, 2010-2012 http://www.holycowstudio.ru");
                    Console.WriteLine("[" + DateTime.Now + "] " + "Press enter or close window!");
                    Console.ReadLine(); //waits for any key
                }
            }
            //and here some exception handlers, try to understand it, they're simple!
            catch (PathTooLongException pathTooLongException)
            {
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + pathTooLongException + "\n");
                if (!silentMode) Console.WriteLine("[" + DateTime.Now + "] " + "Error opening file, see EncodingFixer.log for details!");
                throw;
            }
            catch (DirectoryNotFoundException directoryNotFoundException)
            {
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + directoryNotFoundException + "\n");
                if (!silentMode) Console.WriteLine("[" + DateTime.Now + "] " + "Error opening directory, see EncodingFixer.log for details!");
                throw;
            }
            catch (IOException ioException)
            {
                File.AppendAllText("EncodingFixer.log", "[" + DateTime.Now + "] " + ioException + "\n");
                if (!silentMode) Console.WriteLine("[" + DateTime.Now + "] " + "I/O error, see EncodingFixer.log for details!");
                throw;
            }
        }
    }
}


Откомпиленная версия в аттаче, ярлык запускает программу в тихом режиме.
У вас нет доступа для просмотра вложений в этом сообщении.
Изображение
Форум про инди-игры и их разработку
Аватара пользователя
Andy Ion
UNец
 
Сообщения: 18
Зарегистрирован: 14 авг 2011, 21:04
Откуда: Russia, Sochi
Skype: vermilionx
  • Сайт
  • ICQ

Re: Консольный кодировщик файлов в UTF-8

Сообщение Woolf 11 мар 2012, 15:37

спасибо, полезная штука, а то замучаешься с нотепад++ когда файлов много..
Разработчик theFisherOnline - там, где клюёт
Разработчик Atom Fishing II - Первая 3D MMO про рыбалку
Разработчик Atom Fishing - Рыбалка на поплавок, донку, нахлыст, блесну в постъядерный период.
Аватара пользователя
Woolf
Адепт
 
Сообщения: 7179
Зарегистрирован: 02 мар 2009, 16:59


Вернуться в Исходники (Копилка)

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 2