C#で文字列のエンコーディングを判断する方法はありますか?C#で文字列のエンコーディングを決定する
ファイル名の文字列がありますが、コード化されているかどうかわかりません
Unicode
UTF-16またはシステムのデフォルトのエンコーディングはどうやって確認できますか?
C#で文字列のエンコーディングを判断する方法はありますか?C#で文字列のエンコーディングを決定する
ファイル名の文字列がありますが、コード化されているかどうかわかりません
Unicode
UTF-16またはシステムのデフォルトのエンコーディングはどうやって確認できますか?
Utf8Checkerは純粋な管理コードでこれを行うシンプルなクラスです。 http://utf8checker.codeplex.com
注意:すでに指摘したように、「エンコードの決定」はバイトストリームに対してのみ意味があります。文字列を持っている場合は、最初に文字列を取得するためにエンコーディングを既に知っていたか推測している途中の誰かから既にエンコードされています。
文字列が単純な8-あなたはエンコーディングを使ってそれをデコードすることができますが、通常、バイトを破損せずに取得できます。 – Nyerguds
文字列がどこから来たかによって異なります。 .NET文字列はUnicode(UTF-16)です。たとえば、データベースのデータをバイト配列に読み込むと、違う可能性がある唯一の方法です。
このCodeProjectの記事が参考になります。Detect Encoding for in- and outgoing text
ジョンスキートのStrings in C# and .NETは、.NET文字列の優れた説明です。
それは、非Unicode C++アプリケーションから来た.. CodeProjectの記事は少し複雑すぎるようだが、私は何をしたいのですか..ありがとう.. – krebstar
非常に遅れて来るのが別のオプション、申し訳ありません:
http://www.architectshack.com/TextFileEncodingDetector.ashx
存在する場合、この小さなC#のみのクラスでのBOMを使用し、それ以外の可能なUnicodeのエンコーディングを自動検出しようとする、とのいずれも場合フォールバックUnicodeエンコーディングが可能であるか、または可能性があります。
上記のUTF8Checkerのように聞こえますが、これは同様のことですが、範囲が少し広がります.UTF8の代わりに、可能な他のUnicodeエンコーディング(UTF-16 LEまたはBE)もチェックされていますBOM。
これが誰かを助けることを願っています!
かなり素敵なコード、それは検出をエンコードする私の問題を解決しました:) –
私はこれは少し遅れている知っている - しかし、明確にする:
文字列が本当にエンコーディングを持っていない... .NETで文字列はchar型のオブジェクトのコレクションです。本質的に、それが文字列であれば、既に復号化されている。
しかし、バイトで構成されたファイルの内容を読み込み、それを文字列に変換する場合は、ファイルのエンコーディングを使用する必要があります。
.NETには、ASCII、UTF7、UTF8、UTF32などのエンコードおよびデコードクラスが含まれています。
これらのエンコードのほとんどは、使用されているエンコードタイプを識別するために使用できる特定のバイトオーダーマークを含んでいます。
.NETクラスSystem.IO。StreamReaderは、ストリーム内で使用されるエンコーディングを、それらのバイトオーダーマークを読み取ることによって判断できます。ここ
は一例であり、下記
/// <summary>
/// return the detected encoding and the contents of the file.
/// </summary>
/// <param name="fileName"></param>
/// <param name="contents"></param>
/// <returns></returns>
public static Encoding DetectEncoding(String fileName, out String contents)
{
// open the file with the stream-reader:
using (StreamReader reader = new StreamReader(fileName, true))
{
// read the contents of the file into a string
contents = reader.ReadToEnd();
// return the encoding.
return reader.CurrentEncoding;
}
}
これは、BOMなしでUTF 16を検出するためには機能しません。また、Unicodeエンコードを検出できない場合は、ユーザーのローカルのデフォルトコードページに戻りません。後者を修正するには、 'Encoding.Default'をStreamReaderパラメータとして追加します。その後、コードはBOMなしでUTF8を検出しません。 –
@DanW:BOMのないUTF-16は実際には完成しましたか?私はそれを決して使用しませんでした。それはほとんど何かを開くための災害になるだろう。 – Nyerguds
コードは、次の特徴を有する:
Encoding.GetEncodings();
// Function to detect the encoding for UTF-7, UTF-8/16/32 (bom, no bom, little
// & big endian), and local default codepage, and potentially other codepages.
// 'taster' = number of bytes to check of the file (to save processing). Higher
// value is slower, but more reliable (especially UTF-8 with special characters
// later on may appear to be ASCII initially). If taster = 0, then taster
// becomes the length of the file (for maximum reliability). 'text' is simply
// the string with the discovered encoding applied to the file.
public Encoding detectTextEncoding(string filename, out String text, int taster = 1000)
{
byte[] b = File.ReadAllBytes(filename);
//////////////// First check the low hanging fruit by checking if a
//////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4)
if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); } // UTF-32, big-endian
else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; } // UTF-32, little-endian
else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; } // UTF-16, big-endian
else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; } // UTF-16, little-endian
else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8
else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b,3,b.Length-3); return Encoding.UTF7; } // UTF-7
//////////// If the code reaches here, no BOM/signature was found, so now
//////////// we need to 'taste' the file to see if can manually discover
//////////// the encoding. A high taster value is desired for UTF-8
if (taster == 0 || taster > b.Length) taster = b.Length; // Taster size can't be bigger than the filesize obviously.
// Some text files are encoded in UTF8, but have no BOM/signature. Hence
// the below manually checks for a UTF8 pattern. This code is based off
// the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8
// For our purposes, an unnecessarily strict (and terser/slower)
// implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
// For the below, false positives should be exceedingly rare (and would
// be either slightly malformed UTF-8 (which would suit our purposes
// anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot).
int i = 0;
bool utf8 = false;
while (i < taster - 4)
{
if (b[i] <= 0x7F) { i += 1; continue; } // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks.
if (b[i] >= 0xC2 && b[i] <= 0xDF && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; }
if (b[i] >= 0xE0 && b[i] <= 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; }
if (b[i] >= 0xF0 && b[i] <= 0xF4 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; }
utf8 = false; break;
}
if (utf8 == true) {
text = Encoding.UTF8.GetString(b);
return Encoding.UTF8;
}
// The next check is a heuristic attempt to detect UTF-16 without a BOM.
// We simply look for zeroes in odd or even byte places, and if a certain
// threshold is reached, the code is 'probably' UF-16.
double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10%
int count = 0;
for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++;
if (((double)count)/taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; }
count = 0;
for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++;
if (((double)count)/taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian)
// Finally, a long shot - let's see if we can find "charset=xyz" or
// "encoding=xyz" to identify the encoding:
for (int n = 0; n < taster-9; n++)
{
if (
((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) ||
((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '='))
)
{
if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9;
if (b[n] == '"' || b[n] == '\'') n++;
int oldn = n;
while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z')))
{ n++; }
byte[] nb = new byte[n-oldn];
Array.Copy(b, oldn, nb, 0, n-oldn);
try {
string internalEnc = Encoding.ASCII.GetString(nb);
text = Encoding.GetEncoding(internalEnc).GetString(b);
return Encoding.GetEncoding(internalEnc);
}
catch { break; } // If C# doesn't recognize the name of the encoding, break.
}
}
// If all else fails, the encoding is probably (though certainly not
// definitely) the user's local codepage! One might present to the user a
// list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language
// A full list can be found using Encoding.GetEncodings();
text = Encoding.Default.GetString(b);
return Encoding.Default;
}
私の解決策は、組み込みのものにフォールバックを使用することです。
私はstackoverflowの別の同様の質問への答えから戦略を選んだが、私は今それを見つけることができません。
StreamReaderの組み込みロジックを使用してBOMを最初にチェックします.BOMがある場合、エンコーディングはEncoding.Default
以外のものになります。その結果を信頼する必要があります。
そうでない場合、バイトシーケンスが有効なUTF-8シーケンスであるかどうかをチェックします。そうであれば、UTF-8をエンコーディングとして推測し、そうでなければ、再びデフォルトのASCIIエンコーディングが結果になります。
static Encoding getEncoding(string path) {
var stream = new FileStream(path, FileMode.Open);
var reader = new StreamReader(stream, Encoding.Default, true);
reader.Read();
if (reader.CurrentEncoding != Encoding.Default) {
reader.Close();
return reader.CurrentEncoding;
}
stream.Position = 0;
reader = new StreamReader(stream, new UTF8Encoding(false, true));
try {
reader.ReadToEnd();
reader.Close();
return Encoding.UTF8;
}
catch (Exception) {
reader.Close();
return Encoding.Default;
}
}
注:これはUTF-8エンコーディングが内部で働いていたかを確認するための実験でした。 The solution offered by vilicvaneは、デコードの失敗時に例外をスローするように初期化されたUTF8Encoding
オブジェクトを使用するために、はるかに簡単で、基本的に同じことを行います。
私はUTF-8とWindows-1252を区別するために、コードのこの作品を書きました。しかし、それは巨大なテキストファイルのために使用すべきではありません。それはメモリ全体をロードして完全にスキャンするからです。私は.srt字幕ファイルに使用しましたが、ロードされたエンコーディングに戻すことができます。
refとして関数に渡されるエンコーディングは、ファイルが有効なUTF-8ではないと検出された場合に使用する8ビットフォールバックエンコーディングである必要があります。一般に、Windowsシステムでは、これはWindows-1252になります。実際の有効なascii範囲をチェックするのと同じように、これは決して素晴らしいことではなく、バイトオーダーマークでもUTF-16を検出しません。
ビットごとの検出の背後にある理論は、ここで見つけることができます: https://ianthehenry.com/2015/1/17/decoding-utf-8/
基本的には、最初のバイトのビット範囲は、それがUTF-8エンティティの一部であるどのように多くの後に決定します。これらのバイトの後は、常に同じビット範囲内にあります。
/// <summary>
/// Detects whether the encoding of the data is valid UTF-8 or ascii. If detection fails, the text is decoded using the given fallback encoding.
/// Bit-wise mechanism for detecting valid UTF-8 based on https://ianthehenry.com/2015/1/17/decoding-utf-8/
/// Note that pure ascii detection should not be trusted: it might mean the file is meant to be UTF-8 or Windows-1252 but simply contains no special characters.
/// </summary>
/// <param name="docBytes">The bytes of the text document.</param>
/// <param name="encoding">The default encoding to use as fallback if the text is detected not to be pure ascii or UTF-8 compliant. This ref parameter is changed to the detected encoding, or Windows-1252 if the given encoding parameter is null and the text is not valid UTF-8.</param>
/// <returns>The contents of the read file</returns>
public static String ReadFileAndGetEncoding(Byte[] docBytes, ref Encoding encoding)
{
if (encoding == null)
encoding = Encoding.GetEncoding(1252);
// BOM detection is not added in this example. Add it yourself if you feel like it. Should set the "encoding" param and return the decoded string.
//String file = DetectByBOM(docBytes, ref encoding);
//if (file != null)
// return file;
Boolean isPureAscii = true;
Boolean isUtf8Valid = true;
for (Int32 i = 0; i < docBytes.Length; i++)
{
Int32 skip = TestUtf8(docBytes, i);
if (skip != 0)
{
if (isPureAscii)
isPureAscii = false;
if (skip < 0)
isUtf8Valid = false;
else
i += skip;
}
// if already detected that it's not valid utf8, there's no sense in going on.
if (!isUtf8Valid)
break;
}
if (isPureAscii)
encoding = new ASCIIEncoding(); // pure 7-bit ascii.
else if (isUtf8Valid)
encoding = new UTF8Encoding(false);
// else, retain given fallback encoding.
return encoding.GetString(docBytes);
}
/// <summary>
/// Tests if the bytes following the given offset are UTF-8 valid, and returns
/// the extra amount of bytes to skip ahead to do the next read if it is
/// (meaning, detecting a single-byte ascii character would return 0).
/// If the text is not UTF-8 valid it returns -1.
/// </summary>
/// <param name="binFile">Byte array to test</param>
/// <param name="offset">Offset in the byte array to test.</param>
/// <returns>The amount of extra bytes to skip ahead for the next read, or -1 if the byte sequence wasn't valid UTF-8</returns>
public static Int32 TestUtf8(Byte[] binFile, Int32 offset)
{
Byte current = binFile[offset];
if ((current & 0x80) == 0)
return 0; // valid 7-bit ascii. Added length is 0 bytes.
else
{
Int32 len = binFile.Length;
Int32 fullmask = 0xC0;
Int32 testmask = 0;
for (Int32 addedlength = 1; addedlength < 6; addedlength++)
{
// This code adds shifted bits to get the desired full mask.
// If the full mask is [111]0 0000, then test mask will be [110]0 0000. Since this is
// effectively always the previous step in the iteration I just store it each time.
testmask = fullmask;
fullmask += (0x40 >> addedlength);
// Test bit mask for this level
if ((current & fullmask) == testmask)
{
// End of file. Might be cut off, but either way, deemed invalid.
if (offset + addedlength >= len)
return -1;
else
{
// Lookahead. Pattern of any following bytes is always 10xxxxxx
for (Int32 i = 1; i <= addedlength; i++)
{
// If it does not match the pattern for an added byte, it is deemed invalid.
if ((binFile[offset + i] & 0xC0) != 0x80)
return -1;
}
return addedlength;
}
}
}
// Value is greater than the start of a 6-byte utf8 sequence. Deemed invalid.
return -1;
}
}
また、 'if((current&0xE0)== 0xC0){...}のあとに最後の' else'文もありませんelse if((current&0xF0)== 0xE0){...} else if((current &0xF0)== 0xE0){...} else if((current&0xF8)== 0xF0){...} '。私は、 'else'の場合はutf8:isUtf8Valid = false;'が無効であると考えます。あなたは? – hal
@hal Ah、true ...私は自分のコードを、より一般的な(そしてより高度な)システムで更新したので、最大3になるループを使用しますが、技術的にはさらにループするように変更することができます(仕様は少し不明です) UTF-8を最大6バイトまで拡張することは可能ですが、現在の実装では3つしか使用されていません)、このコードを更新しませんでした。 – Nyerguds
@hal新しいソリューションにアップデートしました。原則は同じですが、ビットマスクは、明示的にコードで書き出されるのではなく、ループで作成され、チェックされます。 – Nyerguds
SimpleHelpers.FileEncoding Nugetパッケージは、デッドシンプルなAPIにC# port of the Mozilla Universal Charset Detectorをラップ:あなたはUnicodeで "エンコード" することはできません
var encoding = FileEncoding.DetectFileEncoding(txtFile);
これはもっと高くなるはずですが、非常に簡単な解決法を提供します。 – buddybubble
。また、他の事前情報なしに、指定されたStringのエンコーディングを自動的に判断する方法はありません。 – NicDumZ
"Unicodeでエンコードすることはできません" - UnicodeをUTF-16(または他の特定のUTF *)として解釈すると、コードポイントを一連のバイト(=エンコード)として書くことができます。 –
どのようにそのような近似を書くことができますか? UTF-16は* Unicodeデータを*エンコードする方法の1つです。あなたは "Unicode-encode"することはできません。 UnicodeはUTF- *ではありません。 UTF- *はUnicodeではありません。申し訳ありませんが、このような近似を書き続けている場合、どのようにUnicode関連の動作が変わるのでしょうか?初心者は暗いUnicodeモンスターにいつも混乱し、物事は変わらないでしょう。正確にしましょう。 – NicDumZ