|
| 1 | +using System.IO; |
| 2 | +using System.Linq; |
| 3 | +using System.Text.RegularExpressions; |
| 4 | + |
| 5 | +// ReSharper disable once CheckNamespace |
| 6 | +namespace System.Text |
| 7 | +{ |
| 8 | + public static class FileInfoExtensions |
| 9 | + { |
| 10 | + public static readonly Regex UnicodeLetters; |
| 11 | + public static readonly Regex AnsiLatin1Mangled; |
| 12 | + |
| 13 | + /// <summary> |
| 14 | + /// Initializes the <see cref="FileInfoExtensions"/> class. |
| 15 | + /// </summary> |
| 16 | + static FileInfoExtensions() |
| 17 | + { |
| 18 | + AnsiLatin1Mangled = new Regex(@"[ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿŸ]", RegexOptions.Compiled | RegexOptions.Multiline); |
| 19 | + UnicodeLetters = new Regex(@"\p{L}", RegexOptions.Compiled | RegexOptions.Multiline); |
| 20 | + } |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Tries the get file encoding. |
| 24 | + /// </summary> |
| 25 | + /// <param name="file">The file.</param> |
| 26 | + /// <param name="encoding">The encoding.</param> |
| 27 | + /// <returns></returns> |
| 28 | + /// <exception cref="ArgumentException">file</exception> |
| 29 | + public static bool TryGetEncoding(this FileInfo file, out Encoding encoding) |
| 30 | + { |
| 31 | + if (null == file || !file.Exists) |
| 32 | + throw new ArgumentException($"{nameof(file)} must be a valid path to a file!"); |
| 33 | + |
| 34 | + var bytes = new byte[10]; |
| 35 | + using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) |
| 36 | + { |
| 37 | + fs.Read(bytes, 0, 10); |
| 38 | + fs.Close(); |
| 39 | + } |
| 40 | + |
| 41 | + switch (bytes) |
| 42 | + { |
| 43 | + case var utf7 when 0x2B == utf7[0] && 0x2F == utf7[1] && 0x76 == utf7[2]: |
| 44 | + encoding = Encoding.UTF7; |
| 45 | + break; |
| 46 | + |
| 47 | + case var utf32 when 0 == utf32[0] && 0 == utf32[1] && 0xFE == utf32[2] && 0xFF == utf32[3]: |
| 48 | + encoding = Encoding.UTF32; |
| 49 | + break; |
| 50 | + |
| 51 | + case var unicode when 0xFE == unicode[0] && 0xFF == unicode[1]: |
| 52 | + encoding = Encoding.GetEncoding(1201); // 1201 unicodeFFFE Unicode (UTF-16BE) |
| 53 | + break; |
| 54 | + |
| 55 | + case var unicode when 0xFF == unicode[0] && 0xFE == unicode[1]: |
| 56 | + encoding = Encoding.GetEncoding(1200); // 1200 UTF-16 Unicode (UTF-16LE) |
| 57 | + break; |
| 58 | + |
| 59 | + case var utf8 when HasBomMarker(utf8): |
| 60 | + encoding = new UTF8Encoding(true); // UTF-8 with BOM |
| 61 | + break; |
| 62 | + |
| 63 | + case var _ when file.IsInUtf8(): |
| 64 | + encoding = new UTF8Encoding(false); // UTF-8 without BOM |
| 65 | + break; |
| 66 | + |
| 67 | + case var _ when file.IsInAnsiLatin1(): |
| 68 | + encoding = Encoding.GetEncoding(1252); // UTF-8 without BOM |
| 69 | + break; |
| 70 | + |
| 71 | + default: |
| 72 | + encoding = null; |
| 73 | + return false; |
| 74 | + } |
| 75 | + |
| 76 | + return true; |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Gets the encoding. |
| 81 | + /// </summary> |
| 82 | + /// <param name="file">The file.</param> |
| 83 | + /// <param name="throwIfNotDetected">if set to <c>true</c> [throws an exception if encoding is not detected].</param> |
| 84 | + /// <returns> |
| 85 | + /// Detected file encoding or null detection failed |
| 86 | + /// </returns> |
| 87 | + /// <exception cref="ArgumentException">file</exception> |
| 88 | + /// <exception cref="InvalidDataException"></exception> |
| 89 | + public static Encoding GetEncoding(this FileInfo file, bool throwIfNotDetected = false) |
| 90 | + { |
| 91 | + if (null == file || !file.Exists) |
| 92 | + throw new ArgumentException($"{nameof(file)} must be a valid path to a file!"); |
| 93 | + |
| 94 | + var encoding = (file.TryGetEncoding(out var fileEncoding)) |
| 95 | + ? fileEncoding |
| 96 | + : null; |
| 97 | + |
| 98 | + if (null == encoding && throwIfNotDetected) |
| 99 | + { |
| 100 | + throw new InvalidDataException( |
| 101 | + $"Unable to detect encoding automatically of the following shared parameter file: {file.FullName}. " + |
| 102 | + "Most likely it's a non-Latin ANSI, e.g. ANSI Cyrillic, Hebrew, Arabic, Greek, Turkish, Vietnamese etc" |
| 103 | + ); |
| 104 | + } |
| 105 | + |
| 106 | + return encoding; |
| 107 | + } |
| 108 | + |
| 109 | + /// <summary> |
| 110 | + /// Determines whether [is in ANSI latin1] [the specified thresh hold]. |
| 111 | + /// </summary> |
| 112 | + /// <param name="file">The file.</param> |
| 113 | + /// <param name="mangledCharThreshold">The threshold of mangled characters.</param> |
| 114 | + /// <returns> |
| 115 | + /// <c>true</c> if [file is ANSI Latin1-encoded] and [the number of mangled characters is lower than specified threshold]; otherwise, <c>false</c>. |
| 116 | + /// </returns> |
| 117 | + /// <exception cref="ArgumentException">file</exception> |
| 118 | + public static bool IsInAnsiLatin1(this FileInfo file, double mangledCharThreshold = 60.0) |
| 119 | + { |
| 120 | + if (null == file || !file.Exists) |
| 121 | + throw new ArgumentException($"{nameof(file)} must be a valid path to a file!"); |
| 122 | + |
| 123 | + var ansiLatin1Encoding = Encoding.GetEncoding(1252); |
| 124 | + var ansiText = File.ReadAllText(file.FullName, ansiLatin1Encoding); |
| 125 | + |
| 126 | + var unicodeLettersFound = UnicodeLetters.Matches(ansiText); |
| 127 | + var ansiMangledFound = AnsiLatin1Mangled.Matches(ansiText); |
| 128 | + var matchRate = ansiMangledFound.Count * 100 / unicodeLettersFound.Count; |
| 129 | + return (matchRate <= mangledCharThreshold); |
| 130 | + } |
| 131 | + |
| 132 | + /// <summary> |
| 133 | + /// Determines whether [has UTF-8 BOM marker]. |
| 134 | + /// </summary> |
| 135 | + /// <param name="file">The file.</param> |
| 136 | + /// <returns> |
| 137 | + /// <c>true</c> if [the specified file] [has UTF-8 BOM marker]; otherwise, <c>false</c>. |
| 138 | + /// </returns> |
| 139 | + /// <exception cref="ArgumentException">file</exception> |
| 140 | + public static bool HasBomMarker(this FileInfo file) |
| 141 | + { |
| 142 | + if (null == file || !file.Exists) |
| 143 | + throw new ArgumentException($"{nameof(file)} must be a valid path to a file!"); |
| 144 | + |
| 145 | + var buffer = new byte[10]; |
| 146 | + using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) |
| 147 | + { |
| 148 | + fs.Read(buffer, 0, 10); |
| 149 | + fs.Close(); |
| 150 | + } |
| 151 | + |
| 152 | + return 0xEF == buffer[0] && 0xBB == buffer[1] && 0xBF == buffer[2]; |
| 153 | + } |
| 154 | + |
| 155 | + /// <summary> |
| 156 | + /// Determines whether [has UTF-8 BOM arker] [the specified bytes]. |
| 157 | + /// </summary> |
| 158 | + /// <param name="bytes">The bytes.</param> |
| 159 | + /// <returns> |
| 160 | + /// <c>true</c> if [the specified bytes] [has UTF-8 BOM marker]; otherwise, <c>false</c>. |
| 161 | + /// </returns> |
| 162 | + /// <exception cref="ArgumentException">bytes</exception> |
| 163 | + public static bool HasBomMarker(byte[] bytes) |
| 164 | + { |
| 165 | + if (bytes == null || !bytes.Any()) |
| 166 | + throw new ArgumentException($"{nameof(bytes)} must be a non-empty array of bytes!"); |
| 167 | + |
| 168 | + return 0xEF == bytes[0] && 0xBB == bytes[1] && 0xBF == bytes[2]; |
| 169 | + } |
| 170 | + |
| 171 | + /// <summary> |
| 172 | + /// Determines whether [is in UTF-8]. |
| 173 | + /// </summary> |
| 174 | + /// <param name="file">The file.</param> |
| 175 | + /// <returns> |
| 176 | + /// <c>true</c> if[the specified file] [is in UTF-8]; otherwise, <c>false</c>. |
| 177 | + /// </returns> |
| 178 | + /// <exception cref="ArgumentException">file</exception> |
| 179 | + public static bool IsInUtf8(this FileInfo file) |
| 180 | + { |
| 181 | + if (null == file || !file.Exists) |
| 182 | + throw new ArgumentException($"{nameof(file)} must be a valid path to a file!"); |
| 183 | + |
| 184 | + try |
| 185 | + { |
| 186 | + using (var fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) |
| 187 | + { |
| 188 | + using (var streamReader = new StreamReader(fileStream, new UTF8Encoding(file.HasBomMarker(), true), true)) |
| 189 | + { |
| 190 | + streamReader.ReadToEnd(); |
| 191 | + } |
| 192 | + } |
| 193 | + return true; |
| 194 | + } |
| 195 | + catch (DecoderFallbackException) |
| 196 | + { |
| 197 | + return false; |
| 198 | + } |
| 199 | + } |
| 200 | + } |
| 201 | +} |
0 commit comments