在我的开发机器(Win7 x64)上按预期工作的小型测试程序在Server 2012计算机上的行为完全不同。谁能告诉我为什么,拜托?
这是代码:
class Program
{
static void w(string msg = "")
{
System.Console.WriteLine(msg);
}
static void w(string fmt, params object[] p)
{
var s = string.Format(fmt, p);
w(s);
}
public static string BytesToString(byte[] barr)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Length : {0} ", barr.Length);
for (int i = 0; i < barr.Length; ++i)
{
byte b = barr[i];
sb.AppendFormat("[{0:0000}] {1:X2} ", i, b);
}
return sb.ToString();
}
static void Main(string[] args)
{
string test_string = "123456789";
// Remove the BOM (Byte Order Marker)
byte[] baUTF8 = Encoding.UTF8.GetPreamble();
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(baUTF8);
w("UTF8 BOM length : {0}", _byteOrderMarkUtf8.Length);
w(BytesToString(baUTF8));
if (test_string.StartsWith(_byteOrderMarkUtf8))
{
w("Test string starts with BOM for UTF8");
w("Removing UTF8 BOM");
w("Length : {0}", test_string.Length);
test_string = test_string.Remove(0, _byteOrderMarkUtf8.Length);
w("Length : {0}", test_string.Length);
}
else
{
w("Test string does not start with BOM for UTF8");
}
w();
byte[] baUTF16 = Encoding.Unicode.GetPreamble();
string _byteOrderMarkUNC = Encoding.Unicode.GetString(baUTF16);
w("UTF16 BOM length : {0}", _byteOrderMarkUNC.Length);
w(BytesToString(baUTF16));
if (test_string.StartsWith(_byteOrderMarkUNC))
{
w("Test string starts with BOM for UTF16");
w("Removing UTF16 BOM");
w("Length : {0}", test_string.Length);
test_string = test_string.Remove(0, _byteOrderMarkUNC.Length);
w("Length : {0}", test_string.Length);
}
else
{
w("Test string does not start with BOM for UTF16");
}
w();
w("Hit RETURN to end the program.");
w();
System.Console.ReadLine();
}
} // class Program
这些是我机器上的(预期)结果:
UTF8 BOM length : 1
Length : 3 [0000] EF [0001] BB [0002] BF
Test string does not start with BOM for UTF8
UTF16 BOM length : 1
Length : 2 [0000] FF [0001] FE
Test string does not start with BOM for UTF16
Hit RETURN to end the program.
这些是Server 2012计算机上的古怪涂鸦结果:
UTF8 BOM length : 1
Length : 3 [0000] EF [0001] BB [0002] BF
Test string starts with BOM for UTF8
Removing UTF8 BOM
Length : 9
Length : 8
UTF16 BOM length : 1
Length : 2 [0000] FF [0001] FE
Test string starts with BOM for UTF16
Removing UTF16 BOM
Length : 8
Length : 7
Hit RETURN to end the program.
感激地收到任何评论。
谢谢,
亚当