Advertisement
liartie

Untitled

Sep 23rd, 2022
1,085
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. using System.Text;
  2.  
  3. namespace Task2
  4. {
  5.     public class Task2
  6.     {
  7.         public static Tuple<Encoding?, Encoding?> ParseArgs(string[] args)
  8.         {
  9.             var inputEncoding = Encoding.GetEncoding(args[1]);
  10.             var outputEncoding = Encoding.GetEncoding(args[2]);
  11.             return new Tuple<Encoding?, Encoding?>(inputEncoding, outputEncoding);
  12.         }
  13.  
  14.         public static String ReadFile(string filename, Encoding encoding)
  15.         {
  16.             var text = File.ReadAllText(filename, encoding);
  17.             return text;
  18.         }
  19.  
  20.         public static String Convert(String lines, Tuple<Encoding, Encoding> encodings)
  21.         {
  22.             Encoding inputEncoding = encodings.Item1;
  23.             Encoding outputEncoding = encodings.Item2;
  24.  
  25.             byte[] inputBytes = inputEncoding.GetBytes(lines);
  26.             byte[] outputBytes = Encoding.Convert(inputEncoding, outputEncoding, inputBytes);
  27.             char[] outputChars = new char[outputEncoding.GetCharCount(outputBytes, 0, outputBytes.Length)];
  28.             outputEncoding.GetChars(outputBytes, 0, outputBytes.Length, outputChars, 0);
  29.             string outputString = new string(outputChars);
  30.             Console.WriteLine("Original string: {0}", lines);
  31.             Console.WriteLine("–°onverted string: {0}", outputString);
  32.             return outputString;
  33.         }
  34.  
  35.         public static void FileOutput(string filename, String lines, Encoding encoding)
  36.         {
  37.             File.WriteAllText(filename, lines, encoding);
  38.         }
  39.        
  40.         public static void FileOutputNoEncoding(string filename, String lines)
  41.         {
  42.             File.WriteAllText(filename, lines);
  43.         }
  44.         public static void Main(string[] args)
  45.         {
  46.             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  47.             var encodings = ParseArgs(args);
  48.             var lines = ReadFile(args[0], encodings.Item1);
  49.             if (encodings.Item1.Equals(Encoding.GetEncoding("windows-1251")))
  50.             {
  51.                 var converted = Convert(lines, encodings);
  52.                 FileOutputNoEncoding(args[0], lines);
  53.             }
  54.            
  55.             else FileOutput(args[0], lines, encodings.Item2);
  56.         }
  57.     }
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement