Determine the encoding format of uploaded txt files (Text garbled solution), and txt encoding format
Description
You can use ajax or browse to upload a text file. When uploading a text file, c # may encounter Chinese garbled characters due to different text formats.
Solution
Determine the file encoding format by uploading the file stream, and obtain the text content in the corresponding encoding format.
# Region checks the encoding type of a given file stream
/// <Summary>
/// Determine the encoding type of a given file stream
/// </Summary>
/// <Param name = "fs"> file stream </param>
/// <Returns> file encoding type </returns>
Private string GetType (byte [] fs, out string errorMsg)
{
String reVal = "Default ";
ErrorMsg = "";
If (IsUTF8Bytes (fs, out errorMsg) | (fs [0] = 0xEF & fs [1] = 0xBB & fs [2] = 0xBF ))
{
ReVal = "UTF8 ";
}
Else if (fs [0] = 0xFE & fs [1] = 0xFF & fs [2] = 0x00)
{
ReVal = "BigEndianUnicode ";
}
Else if (fs [0] = 0xFF & fs [1] = 0xFE & fs [2] = 0x41)
{
ReVal = "Unicode ";
}
Return reVal;
}
# Endregion
// Obtain text content
System. Text. Encoding. Default. GetString (fs)
Test Results
In Windows, most of Default (Default format), UTF8, BigEndianUnicode, and Unicode can be recognized